Configuration API for PubNub Kotlin SDK
Kotlin complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Calling Kotlin methods
Most PubNub Kotlin SDK method invocations return an Endpoint
object, which allows you to decide whether to perform the operation synchronously or asynchronously. You must choose one of these or the operation will not be performed at all.
For example, the following code is valid and will compile, but the publish won't be performed:
pubnub.publish(
message = "this sdk rules!",
channel = "my_channel"
)
To successfully publish a message, you must follow the actual method invocation with whether to perform it synchronously or asynchronously, for example:
pubnub.publish(
message = "this sdk rules!",
channel = "my_channel"
).async { result, status ->
if (status.error) {
// handle error
} else {
// handle successful method result
}
}
Configuration
PNConfiguration
instance is storage for user-provided information which describes further PubNub client behavior. The configuration instance contains additional set of properties which allow performing precise PubNub client configuration.
Method(s)
val config = PNConfiguration(UserId("myUserId"))
To create a pnConfiguration
instance you can use the following properties in the Kotlin SDK:
Properties | Type | Required | Default | Description |
---|---|---|---|---|
subscribeKey | String | Yes | subscribeKey from the Admin Portal. | |
publishKey | String | Optional | publishKey from the Admin Portal (only required if publishing). | |
secretKey | String | Optional | secretKey (only required for access operations, keep away from Android). | |
userId | UserId | Yes | userId to use. The UserId object takes String as an argument. You should set a unique identifier for the user or the device that connects to PubNub.It's a UTF-8 encoded string of up to 64 alphanumeric characters. If you don't set theuserId , you won't be able to connect to PubNub. | |
logVerbosity | PNLogVerbosity | Optional | PNLogVerbosity.NONE | Set PNLogVerbosity.BODY to enable debug logging. To disable debugging use the option PNLogVerbosity.NONE . |
authKey | String | Optional | If Access Manager is utilized, client will use this authKey in all restricted requests. | |
cacheBusting | Boolean | Optional | false | If operating behind a misbehaving proxy, allow the client to shuffle the subdomains. |
secure | Boolean | Optional | true | When true , TLS is enabled. |
connectTimeout | Int | Optional | 5 | How long before the client gives up trying to connect with a subscribe call. The unit is seconds. |
subscribeTimeout | Int | Optional | 310 | The subscribe request timeout. The unit is seconds. |
nonSubscribeRequestTimeout | Int | Optional | 10 | For non subscribe operations (publish , herenow , etc), how long to wait to connect to PubNub before giving up with a connection timeout error. The unit is seconds. |
filterExpression | String | Optional | Feature to subscribe with a custom filter expression. | |
heartbeatNotificationOptions | PNHeartbeatNotificationOptions | Optional | PNHeartbeatNotificationOptions.FAILURES | Heartbeat notification options. By default, the SDK alerts on failed heartbeats (equivalent to PNHeartbeatNotificationOptions.FAILURES ).Other options including all heartbeats ( PNHeartbeatNotificationOptions.ALL ) and no heartbeats (PNHeartbeatNotificationOptions.NONE ). |
origin | String | Optional | Custom origin if needed. | |
presenceTimeout | Int | Optional | 300 | Sets the custom presence server timeout. The value is in seconds, and the minimum value is 20 seconds. When set explicitly, also updates the heartbeatInterval . |
heartbeatInterval | Int | Optional | 0 | Sets a custom heartbeat interval at which to ping the server. Heartbeats are disabled by default, hence the default value is 0 seconds. |
proxy | Proxy | Optional | Instructs the SDK to use a proxy configuration when communicating with PubNub servers. For more details refer to Oracle documentation. | |
proxySelector | ProxySelector | Optional | Sets Java ProxySelector. For more details, refer to Oracle documentation. | |
proxyAuthenticator | Authenticator | Optional | Sets Java Authenticator. For more details refer to Oracle documentation | |
googleAppEngineNetworking | Boolean | Optional | Enable Google App Engine networking. | |
suppressLeaveEvents | Boolean | Optional | false | When true the SDK doesn't send out the leave requests. |
enableEventEngine | Boolean | Optional | true | Whether to use the standardized workflows for subscribe and presence. Read Connection status listeners for more information. |
retryConfiguration | RetryConfiguration | Optional | RetryConfiguration.None | Custom reconnection configuration parameters. You can specify one or more endpoint groups for which the retry policy won't be applied. RetryConfiguration is the type of policy to be used. Available values:
excludedOperations takes a list of RetryableEndpointGroup enums, for example, RetryableEndpointGroup.SUBSCRIBE . For more information, refer to Reconnection Policy. |
maintainPresenceState | Boolean | Optional | true | Whether the state set using PubNub.setPresenceState() should be maintained for the current userId . This option works only when enableEventEngine is set to true . |
cryptoModule | CryptoModule.createAesCbcCryptoModule(cipherKey) CryptoModule.createLegacyCryptoModule(cipherKey) | Optional | None | The cryptography module used for encryption and decryption of messages and files. Takes the cipherKey parameter as argument. For more information, refer to the cryptoModule section. |
reconnectionPolicy | PNReconnectionPolicy | PNReconnectionPolicy.NONE | This parameter is deprecated, use retryConfiguration instead.PNReconnectionPolicy.LINEAR for automatic reconnects.Use PNReconnectionPolicy.NONE to disable automatic reconnects.Use PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval. | |
maximumReconnectionRetries | Int | -1 | This parameter is deprecated, use retryConfiguration instead.The default is -1 which means endless retries.reconnectionPolicy must be set in order for this property to take effect. | |
cipherKey | String | This way of setting this parameter is deprecated, pass it to cryptoModule instead. | ||
useRandomInitializationVector | Boolean | true | This way of setting this parameter is deprecated, pass it to cryptoModule instead. true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload. | |
uuid | String | This parameter is deprecated, use userId instead.UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.If you don't set the UUID , you won't be able to connect to PubNub. |
Disabling random initialization vector
Disable random initialization vector (IV) only for backward compatibility (<6.0.0
) with existing applications. Never disable random IV on new applications.
cryptoModule
cryptoModule
provides encrypt/decrypt functionality for messages and files. From the 7.6.0 release on, you can configure how the actual encryption/decryption algorithms work.
Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256-bit AES-CBC encryption. For more general information on how encryption works, refer to the Message Encryption and File Encryption sections.
If you do not explicitly set the cryptoModule
in your app and have the cipherKey
and useRandomInitializationVector
params set in PubNub config, the client defaults to using the legacy encryption.
Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
cryptoModule
configuration
To configure the cryptoModule
to encrypt all messages/files, you can use the following methods in the Kotlin SDK:
// encrypts using 256-bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
config.cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma")
// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
config.cryptoModule = CryptoModule.createLegacyCryptoModule("enigma")
Your client can decrypt content encrypted using either of the modules. This way, you can interact with historical messages or messages sent from older clients while encoding new messages using the more secure 256-bit AES-CBC cipher.
Older SDK versions
Apps built using the SDK versions lower than 7.6.0 will not be able to decrypt data encrypted using the 256-bit AES-CBC cipher. Make sure to update your clients or encrypt data using the legacy algorithm.
Basic Usage
Required UserId
Always set the UserId
to uniquely identify the user or device that connects to PubNub. This UserId
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId
, you won't be able to connect to PubNub.
val config = PNConfiguration(UserId("myUserId"))
// subscribeKey from Admin Portal
// required
config.subscribeKey = "SubscribeKey"
// publishKey from Admin Portal (only required if publishing)
config.publishKey = "PublishKey"
// secretKey (only required for access operations, keep away from Android)
config.secretKey = "SecretKey"
// the cryptography module used for encryption and decryption
config.cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma")
show all 35 linesInitialization
Add PubNub to your project using one of the procedures defined in Getting Started.
Description
This function is used for initializing the PubNub Client API context. You must call this function before attempting to utilize any API functionality to establish account level credentials such as publishKey
and subscribeKey
.
Methods
To initialize PubNub, you can use the following constructor in the Kotlin SDK:
val config = PNConfiguration(UserId("myUserId"))
Parameter | Type | Required | Description |
---|---|---|---|
PNConfiguration | PNConfiguration | Yes | Refer to configuration for more details. |
Basic Usage
Required UserId
Always set the userId
to uniquely identify the user or device that connects to PubNub. This userId
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId
, you won't be able to connect to PubNub.
val pnConfiguration = PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "my_subkey"
publishKey = "my_pubkey"
secure = true
}
val pubnub = PubNub(pnConfiguration)
Returns
It returns the PubNub instance for invoking PubNub APIs like publish()
, subscribe()
, history()
, hereNow()
, etc.
Other Examples
Initialize a non-secure client
val PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "my_subkey"
publishKey = "my_pubkey"
secure = false
}
val pubnub = PubNub(pnConfiguration)
Initialization for a Read-Only client
val PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "my_subkey"
}
val pubnub = PubNub(pnConfiguration)
Initializing with SSL Enabled
This example demonstrates how to enable PubNub Transport Layer Encryption with SSL
. Just initialize the client with secure
set to true
. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.
val PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "my_subkey"
publishKey = "my_pubkey"
secure = true
}
val pubnub = PubNub(pnConfiguration)
Initializing with Access Manager
Requires Access Manager add-on
This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Secure your secretKey
Anyone with the secretKey
can grant and revoke permissions to your app. Never let your secretKey
be discovered, and to only exchange it / deliver it securely. Only use the secretKey
on secure server-side platforms.
When you init with secretKey
, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
For applications that will administer Access Manager permissions, the API is initialized with the secretKey
as in the following example:
val PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "my_subkey"
publishKey = "my_pubkey"
secretKey = "my_secretkey"
secure = true
}
val pubnub = PubNub(pnConfiguration)
Now that the pubnub
object is instantiated the client will be able to access the Access Manager functions. The pubnub
object will use the secretKey to sign all Access Manager messages to the PubNub Network.
How to Set Proxy
val PNConfiguration(UserId("myUserId")).apply {
subscribeKey = "my_subkey"
publishKey = "my_pubkey"
secretKey = "my_secretkey"
proxy = Proxy(
Proxy.Type.HTTP,
InetSocketAddress("http://mydomain.com", 8080)
)
}
val pubnub = PubNub(pnConfiguration)
Event Listeners
PubNub SDKs provide several sources for real-time updates:
- The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users metadata.
- The
Subscription
object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user. - The
SubscriptionsSet
object can receive updates for all objects for which a list of subscription objects was created.
To facilitate working with those real-time update sources, PubNub SDKs use local representations of server entities that allow you to subscribe and add handlers on a per-entity basis. For more information, refer to Publish & Subscribe.
UserId
These functions are used to set/get a user ID on the fly.
Methods
To set/get userId
you can use the following method(s) in the Kotlin SDK:
val PNConfiguration(UserId("myUserId")).apply
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
userId | UserId | Yes | userId to be used as a device identifier. The UserId object takes String as an argument. If you don't set the userId , you won't be able to connect to PubNub. |
Basic Usage
Required UserId
Always set the userId
to uniquely identify the user or device that connects to PubNub. This userId
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId
, you won't be able to connect to PubNub.
val PNConfiguration(UserId("myUserId")).apply
// get uuid
pnConfiguration.userId
Authentication Key
Setter and getter for users' authentication key.
Method(s)
val pnConfiguration = PNConfiguration()
pnConfiguration.authKey = String
Parameter | Type | Required | Description |
---|---|---|---|
authKey | String | Yes | If Access Manager is utilized, client will use this authKey in all restricted requests. |
Basic Usage
val pnConfiguration = PNConfiguration()
// set authKey
pnConfiguration.authKey = "myAuthKey"
// get authKey
pnConfiguration.authKey
Filter Expression
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.
To set or get message filters, you can use the following method. To learn more about filtering, refer to the Publish Messages documentation.
Method(s)
val pnConfiguration = PNConfiguration()
pnConfiguration.filterExpression = String
Parameter | Type | Required | Description |
---|---|---|---|
filterExpression | String | Yes | PSV2 feature to subscribe with a custom filter expression. |
Basic Usage
val pnConfiguration = PNConfiguration()
// set filterExpression
pnConfiguration.filterExpression = "such=wow"
// get filterExpression
pnConfiguration.filterExpression