Configuration API for 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.
1val channel = pubnub.channel("channelName")
2
3channel.publish("This SDK rules!").async { result ->
4    result.onFailure { exception ->
5        // Handle error
6    }.onSuccess { value ->
7        // Handle successful method result
8    }
9}
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)
1
To create a pnConfiguration instance you can use the following properties in the Kotlin SDK:
| Parameter | Description | 
|---|---|
| subscribeKey*Type:  StringDefault: n/a | subscribeKeyfrom the Admin Portal. | 
| publishKeyType:  StringDefault: n/a | publishKeyfrom the Admin Portal (only required if publishing). | 
| secretKeyType:  StringDefault: n/a | secretKey(only required for access operations, keep away from Android). | 
| userId*Type:  UserIdDefault: n/a | userIdto use. TheUserIdobject takesStringas 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 the userId, you won't be able to connect to PubNub. | 
| customLoggersType:  List<CustomLogger>Default: n/a | Your custom logger implementations. See Logging. | 
| cacheBustingType:  BooleanDefault: false | If operating behind a misbehaving proxy, allow the client to shuffle the subdomains. | 
| secureType:  BooleanDefault: true | When true, TLS is enabled. | 
| connectTimeoutType:  IntDefault: 5 | Maximum time to establish a connection, in seconds. | 
| subscribeTimeoutType:  IntDefault: 310 | Subscribe request timeout, in seconds. | 
| nonSubscribeRequestTimeoutType:  IntDefault: 10 | Non-subscribe request timeout, in seconds. | 
| filterExpressionType:  StringDefault: n/a | Subscribe with a custom filter expression. | 
| heartbeatNotificationOptionsType:  PNHeartbeatNotificationOptionsDefault: 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). | 
| originType:  StringDefault: n/a | Custom origin if needed. To request a custom domain, contact support and follow the request process. | 
| presenceTimeoutType:  IntDefault: 300 | How long the server considers the client alive for presence. The client sends periodic heartbeats to stay active. If no heartbeat arrives within the timeout, the client is marked inactive and a "timeout" event is emitted on the presence channel. Minimum 20seconds. UpdatesheartbeatIntervalwhen set. | 
| heartbeatIntervalType:  IntDefault: 0 | How often the client sends heartbeats. To shorten presence timeout, set roughly to (presenceTimeout / 2) - 1. Minimum3. Default0(disabled). | 
| proxyType:  ProxyDefault: n/a | Instructs the SDK to use a proxy configuration when communicating with PubNub servers. For more details refer to Oracle documentation. | 
| proxySelectorType:  ProxySelectorDefault: n/a | Sets Java ProxySelector. For more details, refer to Oracle documentation. | 
| proxyAuthenticatorType:  AuthenticatorDefault: n/a | Sets Java Authenticator. For more details refer to Oracle documentation | 
| googleAppEngineNetworkingType:  BooleanDefault: n/a | Enable Google App Engine networking. | 
| suppressLeaveEventsType:  BooleanDefault: false | When truethe SDK doesn't send out theleaverequests. | 
| retryConfigurationType:  RetryConfigurationDefault: 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. RetryConfigurationis the type of policy to be used.Available values: 
 excludedOperationstakes a list ofRetryableEndpointGroupenums, for example,RetryableEndpointGroup.SUBSCRIBE.For more information, refer to SDK connection lifecycle. | 
| maintainPresenceStateType:  BooleanDefault: true | Whether the custom presence state information set using pubnub.setPresenceState()should be sent every time the SDK sends a subscribe call. | 
| cryptoModuleType:  CryptoModule.createAesCbcCryptoModule(cipherKey)CryptoModule.createLegacyCryptoModule(cipherKey)Default: None | The cryptography module used for encryption and decryption of messages and files. Takes the cipherKeyparameter as argument.For more information, refer to the cryptoModule section. | 
| includeInstanceIdentifierType:  BooleanDefault: false | Whether to include a PubNubCore.instanceIdwith every request. | 
| includeRequestIdentifierType:  BooleanDefault: true | Whether to include a PubNubCore.requestIdwith every request. | 
| maximumConnectionsType:  Int?Default: n/a | Configures the maximum number of inbound concurrent connections that PubNub will handle. | 
| certificatePinnerType:  CertificatePinnerDefault: n/a | Manages SSL certificates for HTTPS requests. For more details, see OkHttp's CertificatePinner documentation. | 
| sslSocketFactoryType:  SSLSocketFactoryDefault: n/a | Custom SSLSocketFactory used for HTTPS connections. | 
| x509ExtendedTrustManagerType:  X509ExtendedTrustManagerDefault: n/a | Custom X509ExtendedTrust Manager to manage which X509 certificates may be used to authenticate the remote side of a secure socket. | 
| connectionSpecType:  ConnectionSpecDefault: n/a | Specifies which TLS versions and cipher suites are supported for HTTPS. See ConnectionSpec. | 
| hostnameVerifierType:  HostnameVerifierDefault: n/a | Hostname Verifier, checks whether the hostname is allowed within an SSL session. | 
| fileMessagePublishRetryLimitType:  IntDefault: 5 | Defines how many times publishing of file messages should retry automatically before failure. | 
| dedupOnSubscribeType:  BooleanDefault: n/a | Indicates if message deduplication feature is enabled on subscription. | 
| maximumMessagesCacheSizeType:  IntDefault: n/a | Specifies the maximum size of the messages cache. | 
| pnsdkSuffixesType:  Map<String, String>Default: n/a | Maps custom suffixes for SDK identification headers. | 
| managePresenceListManuallyType:  BooleanDefault: n/a | Enables explicit manual management of presence list. Used with ACL on the server-side. | 
| authKeyType:  StringDefault: | 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. authKeyin all restricted requests. | 
cryptoModule
cryptoModule encrypts and decrypts messages and files. From 7.6.0, you can configure the algorithms it uses. By default, encryption is disabled.
Each SDK includes two options: legacy 128‑bit encryption and recommended 256‑bit AES‑CBC. For background, see Message Encryption and File Encryption.
For configuration details, utilities, and examples, see 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.
Sample code
Reference code
Required User ID
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.
1
Value override
You can provide updated values for certain configuration options for a single request to any supported API with overrideConfiguration.
1
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 in Getting Started.
Description
Initialize the PubNub Client API before using any APIs. This sets account-level credentials such as publishKey and subscribeKey.
Methods
Initialize PubNub with:
1
| Parameter | Description | 
|---|---|
| builder*Type:  PNConfiguration | Refer to configuration for more details. | 
Sample code
Required User ID
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.
1
Returns
Returns the PubNub instance to call APIs such as publish(), subscribe(), history(), and hereNow().
Other examples
Initialize a non-secure client
1
Initialization for a Read-Only client
1
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.
1
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:
1
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
1
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 Subscriptionobject can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
- The SubscriptionsSetobject can receive updates for all objects for which a list of subscription objects was created.
To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see Publish & Subscribe.
UserId
These functions are used to set/get a user ID on the fly.
Method(s)
To set/get userId you can use the following method(s) in the Kotlin SDK:
1// Getting the userId
2val userId = pubnub.configuration.userId.value
1
| Parameter | Description | 
|---|---|
| userId*Type:  UserIdDefault: n/a | userIdto be used as a device identifier. TheUserIdobject takesStringas an argument. If you don't set theuserId, you won't be able to connect to PubNub. | 
Sample code
Required User ID
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.
Set UserId
1
Get UserId
1
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)
1
| Parameter | Description | 
|---|---|
| filterExpression*Type:  String | PSV2 feature to subscribewith a custom filter expression. | 
Sample code
1