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
Description
PNConfiguration
instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow performing precise PubNub client configuration.
Method(s)
val pnConfiguration = PNConfiguration()
To create a pnConfiguration
instance you can use the following properties in the Kotlin V4 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). | |
cipherKey | String | Optional | If passed, all communications to and from PubNub will be encrypted. | |
uuid | String | Yes | 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. | |
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. | |
reconnectionPolicy | PNReconnectionPolicy | Optional | PNReconnectionPolicy.NONE | Set to PNReconnectionPolicy.LINEAR for automatic reconnects.Use PNReconnectionPolicy.NONE to disable automatic reconnects.Use PNReconnectionPolicy.EXPONENTIAL to set exponential retry interval. |
maximumReconnectionRetries | Int | Optional | -1 | The 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. |
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. |
useRandomInitializationVector | Boolean | Optional | true | When 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. |
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
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
val pnConfiguration = PNConfiguration()
// 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"
// UUID to be used as a device identifier
// won't connect if not set
pnConfiguration.uuid = "myUniqueUUID"
// Enable Debugging
pnConfiguration.logVerbosity = PNLogVerbosity.BODY
// if Access Manager is utilized, client will use this authKey in all restricted
// requests
pnConfiguration.authKey = "authKey"
// use SSL
pnConfiguration.secure = true
// PSV2 feature to subscribe with a custom filter expression
pnConfiguration.filterExpression = "such=wow"
// heartbeat notifications, by default, the SDK will alert on failed heartbeats.
// other options such as all heartbeats or no heartbeats are supported.
pnConfiguration.heartbeatNotificationOptions = PNHeartbeatNotificationOptions.ALL
pnConfiguration.presenceTimeout = 120
// the number of messages into the payload
pnConfiguration.requestMessageCountThreshold = 100
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 pubnub = PubNub(pnConfiguration)
Parameter | Type | Required | Description |
---|---|---|---|
pnConfiguration | PNConfiguration | Yes | Refer to configuration for more details. |
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
val pnConfiguration = PNConfiguration().apply {
subscribeKey = "my_subkey"
publishKey = "my_pubkey"
secure = true
uuid = "myUniqueUuid"
}
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 = PNConfiguration().apply { subscribeKey = "my_subkey" publishKey = "my_pubkey" secure = false uuid = "myUniqueUuid" } val pubnub = PubNub(pnConfiguration)
Initialization for a Read-Only client:
val pnConfiguration = PNConfiguration().apply { subscribeKey = "my_subkey" } val pubnub = PubNub(pnConfiguration)
-
val pnConfiguration = PNConfiguration().apply { subscribeKey = "my_subkey" publishKey = "my_pubkey" uuid = "myUniqueUuid" } val pubnub = PubNub(pnConfiguration)
Initializing with SSL Enabled: This example demonstrates how to enable PubNub Transport Layer Encryption with
SSL
. Just initialize the client withsecure
set totrue
. 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 = PNConfiguration().apply { subscribeKey = "my_subkey" publishKey = "my_pubkey" secure = true uuid = "myUniqueUuid" } val pubnub = PubNub(pnConfiguration)
- Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Note
Anyone with the
secretKey
can grant and revoke permissions to your app. Never let yoursecretKey
be discovered, and to only exchange it / deliver it securely. Only use thesecretKey
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 PAM permissions, the API is initialized with the
secretKey
as in the following example:val pnConfiguration = PNConfiguration().apply { subscribeKey = "my_subkey" publishKey = "my_pubkey" secretKey = "my_secretkey" uuid = "myUniqueUuid" secure = true } val pubnub = PubNub(pnConfiguration)
Now that the
pubnub
object is instantiated the client will be able to access the PAM functions. Thepubnub
object will use the secretKey to sign all PAM messages to the PubNub Network. -
val pnConfiguration = PNConfiguration().apply { subscribeKey = "my_subkey" publishKey = "my_pubkey" secretKey = "my_secretkey" uuid = "myUniqueUuid" proxy = Proxy( Proxy.Type.HTTP, InetSocketAddress("http://mydomain.com", 8080) ) } val pubnub = PubNub(pnConfiguration)
Event Listeners
Description
You can be notified of connectivity status, message, and presence notifications via the listeners.
Listeners should be added before calling the method.
Adding 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}")
println("Presence channel: ${pnPresenceEventResult.channel}")
println("Presence uuid: ${pnPresenceEventResult.uuid}")
println("Presence timetoken: ${pnPresenceEventResult.timetoken}")
println("Presence occupancy: ${pnPresenceEventResult.occupancy}")
}
override fun message(pubnub: PubNub, pnMessageResult: PNMessageResult) {
println("Message payload: ${pnMessageResult.message}")
println("Message channel: ${pnMessageResult.channel}")
println("Message publisher: ${pnMessageResult.publisher}")
println("Message timetoken: ${pnMessageResult.timetoken}")
}
override fun signal(pubnub: PubNub, pnSignalResult: PNSignalResult) {
println("Signal payload: ${pnSignalResult.message}")
println("Signal channel: ${pnSignalResult.channel}")
println("Signal publisher: ${pnSignalResult.publisher}")
println("Signal timetoken: ${pnSignalResult.timetoken}")
}
override fun messageAction(pubnub: PubNub, pnMessageActionResult: PNMessageActionResult) {
with(pnMessageActionResult.messageAction) {
println("Message action type: $type")
println("Message action value: $value")
println("Message action uuid: $uuid")
println("Message action actionTimetoken: $actionTimetoken")
println("Message action messageTimetoken: $messageTimetoken")
}
println("Message action subscription: ${pnMessageActionResult.subscription}")
println("Message action channel: ${pnMessageActionResult.channel}")
println("Message action timetoken: ${pnMessageActionResult.timetoken}")
}
override fun objects(pubnub: PubNub, objectEvent: PNObjectEventResult) {
println("Object event channel: ${objectEvent.channel}")
println("Object event publisher: ${objectEvent.publisher}")
println("Object event subscription: ${objectEvent.subscription}")
println("Object event timetoken: ${objectEvent.timetoken}")
println("Object event userMetadata: ${objectEvent.userMetadata}")
with(objectEvent.extractedMessage) {
println("Object event event: $event")
println("Object event source: $source")
println("Object event type: $type")
println("Object event version: $version")
}
}
})
Removing 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
Category | Description |
---|---|
PNAcknowledgmentCategory | Used API report success with this status category. |
PNAccessDeniedCategory | Request failed because of access error (active PAM) |
PNTimeoutCategory | Used API didn't received response from server in time. |
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNReconnectedCategory | Subscription loop has been reconnected due some reasons. |
PNUnexpectedDisconnectCategory | Previously started subscribe loop did fail and at this moment client disconnected from real-time data channels. |
PNCancelledCategory | Request was cancelled by user. |
PNBadRequestCategory | The server responded with 400 because the request is malformed. |
PNMalformedResponseCategory | Request received in response non-JSON data. It can be because of publish WiFi hotspot which require authorization or proxy server message. |
PNRequestMessageCountExceededCategory | If requestMessageCountThreshold is set, this status event will arrive each time when the client receives more messages than specified. |
PNReconnectionAttemptsExhausted | The SDK loop has been stopped due maximum reconnection exhausted. |
PNNotFoundCategory | The subscriber gets a 404 from the server. |
PNUnknownCategory | The subscriber gets a 4xx code from the server, other than 400, 403 and 404 |
UUID
Description
These functions are used to set/get a user ID on the fly.
Methods
To set/get UUID
you can use the following method(s) in the Kotlin SDK:
val pnConfiguration = PNConfiguration()
pnConfiguration.uuid = String
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
uuid | String | Yes | UUID to be used as a device identifier. If you don't set the UUID , you won't be able to connect to PubNub. |
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
val pnConfiguration = PNConfiguration()
// set uuid
pnConfiguration.uuid = "myUniqueUUID"
// get uuid
pnConfiguration.uuid
Authentication Key
Description
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-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
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/get 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