Configuration API for PubNub Kotlin SDK

Kotlin V4 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 V4 SDK:

PropertiesTypeRequiredDefaultDescription
subscribeKeyStringYessubscribeKey from the Admin Portal.
publishKeyStringOptionalpublishKey from the Admin Portal (only required if publishing).
secretKeyStringOptionalsecretKey (only required for access operations, keep away from Android).
cipherKeyStringOptionalIf passed, all communications to and from PubNub will be encrypted.
userIdUserIdYesuserId 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 the userId, you won't be able to connect to PubNub.
logVerbosityPNLogVerbosityOptionalPNLogVerbosity.NONESet PNLogVerbosity.BODY to enable debug logging. To disable debugging use the option PNLogVerbosity.NONE.
authKeyStringOptionalIf Access Manager is utilized, client will use this authKey in all restricted requests.
cacheBustingBooleanOptionalfalseIf operating behind a misbehaving proxy, allow the client to shuffle the subdomains.
secureBooleanOptionaltrueWhen true, TLS is enabled.
connectTimeoutIntOptional5How long before the client gives up trying to connect with a subscribe call. The unit is seconds.
subscribeTimeoutIntOptional310The subscribe request timeout. The unit is seconds.
nonSubscribeRequestTimeoutIntOptional10For 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.
filterExpressionStringOptionalFeature to subscribe with a custom filter expression.
heartbeatNotificationOptionsPNHeartbeatNotificationOptionsOptionalPNHeartbeatNotificationOptions.FAILURESHeartbeat 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).
originStringOptionalCustom origin if needed.
reconnectionPolicyPNReconnectionPolicyOptionalPNReconnectionPolicy.NONESet to PNReconnectionPolicy.LINEAR for automatic reconnects.
Use PNReconnectionPolicy.NONE to disable automatic reconnects.
Use PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval.
maximumReconnectionRetriesIntOptional-1The property configures how many times to retry to reconnect before giving up.
The default is -1 which means endless retries.
A reconnectionPolicy must be set in order for this property to take effect.
presenceTimeoutIntOptional300Sets the custom presence server timeout.
The value is in seconds, and the minimum value is 20 seconds. When set explicitly, also updates the heartbeatInterval.
heartbeatIntervalIntOptional0Sets a custom heartbeat interval at which to ping the server.
Heartbeats are disabled by default, hence the default value is 0 seconds.
proxyProxyOptionalInstructs the SDK to use a proxy configuration when communicating with PubNub servers. For more details refer to Oracle documentation.
proxySelectorProxySelectorOptionalSets Java ProxySelector. For more details, refer to Oracle documentation.
proxyAuthenticatorAuthenticatorOptionalSets Java Authenticator. For more details refer to Oracle documentation
googleAppEngineNetworkingBooleanOptionalEnable Google App Engine networking.
suppressLeaveEventsBooleanOptionalfalseWhen true the SDK doesn't send out the leave requests.
useRandomInitializationVectorBooleanOptionaltrueWhen 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.
uuidStringYesThis 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.

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
pnConfiguration.subscribeKey = "SubscribeKey"

// publishKey from Admin Portal (only required if publishing)
pnConfiguration.publishKey = "PublishKey"

// secretKey (only required for access operations, keep away from Android)
pnConfiguration.secretKey = "SecretKey"

// if cipherKey is passed, all communications to/from pubnub will be encrypted
pnConfiguration.cipherKey = "cipherKey"

show all 41 lines

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 config = PNConfiguration(UserId("myUserId"))
ParameterTypeRequiredDescription
PNConfigurationPNConfigurationYesRefer 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

You can be notified of connectivity status, message, and presence notifications via the listeners.

Listeners should be added before calling the method.

Add Listeners

pubnub.addListener(object : SubscribeCallback() {

override fun status(pubnub: PubNub, status: PNStatus) {
println("Status category: ${status.category}")
// PNConnectedCategory, PNReconnectedCategory, PNDisconnectedCategory

println("Status operation: ${status.operation}")
// PNSubscribeOperation, PNHeartbeatOperation

println("Status error: ${status.error}")
// true or false
}

override fun presence(pubnub: PubNub, pnPresenceEventResult: PNPresenceEventResult) {
println("Presence event: ${pnPresenceEventResult.event}")
show all 64 lines

Remove Listeners

val listener = object : SubscribeCallback() {
override fun status(pubnub: PubNub, pnStatus: PNStatus) {}
override fun message(pubnub: PubNub, pnMessageResult: PNMessageResult) {}
// and other callbacks
}

pubnub.addListener(listener)

// some time later
pubnub.removeListener(listener)

Handling Disconnects

The client may disconnect due to unpredictable network conditions.

You can configure automatic reconnection as follows:

pubnub.configuration.reconnectionPolicy = PNReconnectionPolicy.LINEAR
// choose between LINEAR and EXPONENTIAL
// default is NONE

pubnub.configuration.maximumReconnectionRetries = 10
// how many times the client will try to reconnect
// until giving up
// default is infinite

Or manually:

pubnub.addListener(object : SubscribeCallback() {

override fun status(pubnub: PubNub, status: PNStatus) {
if (status.category == PNStatusCategory.PNUnexpectedDisconnectCategory ||
status.category == PNStatusCategory.PNTimeoutCategory
) {
pubnub.reconnect()
}
}

})

Listeners status events

CategoryDescription
PNAcknowledgmentCategoryUsed API report success with this status category.
PNAccessDeniedCategoryRequest failed because of access error (active Access Manager)
PNTimeoutCategoryUsed API didn't received response from server in time.
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNReconnectedCategorySubscription loop has been reconnected due some reasons.
PNUnexpectedDisconnectCategoryPreviously started subscribe loop did fail and at this moment client disconnected from real-time data channels.
PNCancelledCategoryRequest was cancelled by user.
PNBadRequestCategoryThe server responded with 400 because the request is malformed.
PNMalformedResponseCategoryRequest received in response non-JSON data. It can be because of publish WiFi hotspot which require authorization or proxy server message.
PNRequestMessageCountExceededCategoryIf requestMessageCountThreshold is set, this status event will arrive each time when the client receives more messages than specified.
PNReconnectionAttemptsExhaustedThe SDK loop has been stopped due maximum reconnection exhausted.
PNNotFoundCategoryThe subscriber gets a 404 from the server.
PNUnknownCategoryThe subscriber gets a 4xx code from the server, other than 400, 403 and 404

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
ParameterTypeRequiredDefaultDescription
userIdUserIdYesuserId 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
ParameterTypeRequiredDescription
authKeyStringYesIf 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
ParameterTypeRequiredDescription
filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression.

Basic Usage

val pnConfiguration = PNConfiguration()

// set filterExpression
pnConfiguration.filterExpression = "such=wow"

// get filterExpression
pnConfiguration.filterExpression
Last updated on