Configuration API for PubNub Kotlin SDK
Breaking changes in v9.0.0
PubNub Kotlin SDK version 9.0.0 unifies the codebases for Kotlin and Java SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted status events. These changes can impact applications built with previous versions (< 9.0.0
) of the Kotlin SDK.
For more details about what has changed, refer to Java/Kotlin SDK migration guide.
Kotlin complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Request execution
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 invoke the .sync()
or .async()
method on the Endpoint to execute the request, or the operation will not be performed.
val channel = pubnub.channel("channelName")
channel.publish("This SDK rules!").async { result ->
result.onFailure { exception ->
// Handle error
}.onSuccess { value ->
// 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.
Immutable configuration
Once a configuration object has been passed to the PubNub constructor, you can't change its properties.
If you require changing values dynamically consider using value overrides.
Method(s)
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
// config options
}
val pubnub = PubNub.create(builder.build())
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 92 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 . |
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 the server. 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), this property relates to a read timeout that is applied from the moment the connection between a client and the server has been successfully established. It defines a maximum time of inactivity between two data packets when waiting for the server’s response. 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. |
retryConfiguration | RetryConfiguration | Optional | RetryConfiguration.Exponential (subscribe only) | 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 . |
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. |
includeInstanceIdentifier | Boolean | Optional | false | Whether to include a PubNubCore.instanceId with every request. |
includeRequestIdentifier | Boolean | Optional | true | Whether to include a PubNubCore.requestId with every request. |
maximumConnections | Int? | Optional | Configures the maximum number of inbound concurrent connections that PubNub will handle. | |
certificatePinner | CertificatePinner | Optional | Manages SSL certificates for HTTPS requests. For more details, see OkHttp's CertificatePinner documentation. | |
httpLoggingInterceptor | HttpLoggingInterceptor | Optional | Provides HTTP request-response logging. See HttpLoggingInterceptor. | |
sslSocketFactory | SSLSocketFactory | Optional | Custom SSLSocketFactory used for HTTPS connections. | |
x509ExtendedTrustManager | X509ExtendedTrustManager | Optional | Custom X509ExtendedTrust Manager to manage which X509 certificates may be used to authenticate the remote side of a secure socket. | |
connectionSpec | ConnectionSpec | Optional | Specifies which TLS versions and cipher suites are supported for HTTPS. See ConnectionSpec. | |
hostnameVerifier | HostnameVerifier | Optional | Hostname Verifier, checks whether the hostname is allowed within an SSL session. | |
fileMessagePublishRetryLimit | Int | Optional | 5 | Defines how many times publishing of file messages should retry automatically before failure. |
dedupOnSubscribe | Boolean | Optional | Indicates if message deduplication feature is enabled on subscription. | |
maximumMessagesCacheSize | Int | Optional | Specifies the maximum size of the messages cache. | |
pnsdkSuffixes | Map<String, String> | Optional | Maps custom suffixes for SDK identification headers. | |
managePresenceListManually | Boolean | Optional | Enables explicit manual management of presence list. Used with ACL on the server-side. | |
authKey | String | This parameter is deprecated. Refer to Manage Access to understand the permission authorization flow and to Kotlin Access Manager API for an overview of the API. authKey in all restricted requests. |
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:
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
// encrypts using 256-bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma")
}
val pubnub = PubNub.create(builder.build())
// OR
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
cryptoModule = CryptoModule.createLegacyCryptoModule("enigma")
}
val pubnub = PubNub.create(builder.build())
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
secretKey = "SecretKey"
cryptoModule = CryptoModule.createAesCbcCryptoModule("enigma")
logVerbosity = PNLogVerbosity.BODY
secure = true
heartbeatNotificationOptions = PNHeartbeatNotificationOptions.ALL
}
val pubnub = PubNub.create(builder.build())
Value override
You can provide updated values for certain configuration options for a single request to any supported API with overrideConfiguration
.
// publish
pubnub.publish("myChannel", "mymessage").overrideConfiguration {
publishKey = "overridePublishKey"
}.sync()
The configuration options you can override include:
subscribeKey
publishKey
secretKey
retryConfiguration
userId
includeInstanceIdentifier
includeRequestIdentifier
cryptoModule
connectTimeout
nonSubscribeReadTimeout
Initialization
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
}
val pubnub = PubNub.create(builder.build())
Parameter | Type | Required | Description |
---|---|---|---|
builder | 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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
}
val pubnub = PubNub.create(builder.build())
Returns
It returns the PubNub instance for invoking PubNub APIs like publish()
, subscribe()
, history()
, hereNow()
, etc.
Other Examples
Initialize a non-secure client
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
secure = false
}
val pubnub = PubNub.create(builder.build())
Initialization for a Read-Only client
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey")
val pubnub = PubNub.create(builder.build())
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
secure = true
}
val pubnub = PubNub.create(builder.build())
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
secretKey = "SecretKey"
secure = true
}
val pubnub = PubNub.create(builder.build())
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
secretKey = "SecretKey"
proxy = Proxy(
Proxy.Type.HTTP,
InetSocketAddress("http://mydomain.com", 8080)
)
}
val pubnub = PubNub.create(builder.build())
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey")
val pubnub = PubNub.create(builder.build())
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey")
val pubnub = PubNub.create(builder.build())
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 builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
filterExpression = "someExpression"
}
val pubnub = PubNub.create(builder.build())
Parameter | Type | Required | Description |
---|---|---|---|
filterExpression | String | Yes | PSV2 feature to subscribe with a custom filter expression. |
Basic Usage
val builder = PNConfiguration.builder(UserId("abc"), "subscribeKey") {
publishKey = "publishKey"
filterExpression = "such=wow"
}
val pubnub = PubNub.create(builder.build())