Presence 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.

Presence enables you to track the online and offline status of users and devices in real time and store custom state information. Presence provides authoritative information on:

  • When a user has joined or left a channel
  • Who, and how many, users are subscribed to a particular channel
  • Which channel(s) an individual user is subscribed to
  • Associated state information for these users

Learn more about our Presence feature here.

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
}
}

Here Now

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the hereNow() function in your application.

Cache

This method has a 3 second response cache time.

Method(s)

To call Here Now you can use the following methods in the Kotlin SDK:

pubnub.hereNow(
channels: List<String>,
channelGroups: List<String>,
includeState: Boolean,
includeUUIDs: Boolean
).async { result -> }
ParameterTypeRequiredDefaultDescription
channelsList<String>OptionalThe channels to get the 'here now' details of.
channelGroupsList<String>OptionalThe channelGroups to get the 'here now' details of.
includeStateBooleanOptionalfalseIf true, the response will include the presence states of the users for channels/channelGroups.
includeUUIDsBooleanOptionaltrueIf true, the response will include the UUIDs of the connected clients.

Basic Usage

Get a list of UUIDs subscribed to channel

pubnub.hereNow(
channels = listOf("ch1", "ch2"),
includeUUIDs = true,
includeState = true
).async { result ->
result.onFailure { exception ->
// Handle error
}.onSuccess { value: PNHereNowResult ->
value!!.channels.values.forEach { channelData ->
println("---")
println("Channel: ${channelData.channelName}")
println("Occupancy: ${channelData.occupancy}")
println("Occupants:")
channelData.occupants.forEach { o ->
println("UUID: ${o.uuid}, state: ${o.state}")
show all 19 lines

Returns

The hereNow() operation returns a PNHereNowResult? which contains the following operations:

MethodTypeDescription
totalChannelsIntTotal channels
totalOccupancyIntTotal occupancy
channelsMap<String, PNHereNowChannelData>A map with values of PNHereNowChannelData for each channel. See PNHereNowChannelData for more details.

PNHereNowChannelData

MethodTypeDescription
channelNameStringChannel name
occupancyIntOccupancy of the channel
occupantsList<PNHereNowOccupantData>A list of PNHereNowOccupantData, see PNHereNowOccupantData for more details.

PNHereNowOccupantData

MethodTypeDescription
uuidStringUUID of the user
stateJsonElement?State of the user

Other Examples

Returning State

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.hereNow(
channels = listOf("ch1", "ch2"),
includeState = true
).async { result -> }

Example response:

if (!status.error) {
result!!.channels.values.forEach { channelData ->
channelData.channelName // ch1
channelData.occupancy // 3
channelData.occupants.forEach { o ->
o.uuid // some_uuid, returned by default
o.state // {"data":{"isTyping":true}}, requested
}
}
} else {
// handle error
status.exception?.printStackTrace()
}

Return Occupancy Only

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

You can return only the occupancy information for a single channel by specifying the channel and setting UUIDs to false:

pubnub.hereNow(
channels = listOf("my_channel"), // who is present on those channels?
includeUUIDs = false, // if false, only shows occupancy count
includeState = false // include state with request (false by default)
).async { result -> }

Example response:

if (!status.error) {
result!!.channels.values.forEach { channelData ->
channelData.channelName // ch1
channelData.occupancy // 3
}
} else {
// handle error
status.exception?.printStackTrace()
}

Here Now for Channel Groups

pubnub.hereNow(
channelGroups = listOf("cg1", "cg2", "cg3"), // who is present on those channels groups
includeState = true, // include state with request (false by default)
includeUUIDs = true // if false, only shows occupancy count
).async { result -> }

Example response:

if (!status.error) {
result!!.totalOccupancy // 12
} else {
// handle error
status.exception?.printStackTrace()
}

Where Now

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

You can obtain information about the current list of channels to which a UUID is subscribed to by calling the whereNow() function in your application.

Timeout events

If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) within the heartbeat window no timeout event is generated.

Method(s)

To call whereNow() you can use the following method(s) in the Kotlin SDK:

pubnub.whereNow(
uuid: String
).async { result -> }
ParameterTypeRequiredDefaultDescription
uuidStringOptionalUUID of the user to get its current channel subscriptions.

Basic Usage

You simply need to define the uuid and the callback function to be used to send the data to as in the example below.

Get a list of channels a UUID is subscribed to

pubnub.whereNow()
.async { result ->
result.onFailure { exception ->
// Handle error
}.onSuccess { value ->
// Handle successful method result
}

Returns

The whereNow() operation returns a PNWhereNowResult? which contains the following operations:

MethodTypeDescription
channelsList<String>List of channels where the uuid is present.

Other Examples

Obtain information about the current list of channels of some other UUID

pubnub.whereNow(
uuid = "someUuid"
).async { result ->
result.onFailure { exception ->
// Handle error
}.onSuccess { value ->
// Handle successful method result
}

User State

Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

The state API is used to set/get key/value pairs specific to a subscriber uuid.

State information is supplied as a JSON object of key/value pairs.

Presence state format

Presence state must be expressed as a JsonObject. When calling setState, be sure to supply an initialized JsonObject or POJO which can be serialized to a JsonObject.

Method(s)

To set the state, call setPresenceState() you can use the following method(s) in the Kotlin SDK:

Set State

pubnub.setPresenceState(
channels: List<String>,
channelGroups: List<String>,
state: Any,
uuid: String
).async { result -> }
ParameterTypeRequiredDefaultDescription
channelsList<String>OptionalChannels to set state to.
channelGroupsList<String>OptionalChannel groups to set state to.
stateAnyOptionalThe state to set.
uuidStringOptionalThe UUID to set state for.

Get State

pubnub.getPresenceState(
channels: List<String>,
channelGroups: List<String>,
uuid: String
).async { result -> }

To get the state, call getPresenceState() you can use the following method(s) in the Kotlin SDK:

ParameterTypeRequiredDefaultDescription
channelsList<String>OptionalChannels to get state of.
channelGroupsList<String>OptionalChannel groups to get state of.
uuidStringOptionalThe UUID to get state for.

Basic Usage

//set state
pubnub.setPresenceState(
channels = listOf("my_channel"),
state = mapOf("is_typing" to "true")
// if no uuid supplied, own is used
).async { result -> }


// get state
pubnub.getPresenceState(
channels = listOf("ch1", "ch2", "ch3"), // channels to fetch state for
uuid = "such_uuid" // uuid of user to fetch, or own uuid by default
).async { result -> }

Returns

The setPresenceState() operation returns a PNSetStateResult? which contains the following operations:

MethodTypeDescription
stateJsonElementThe actual state object

The getPresenceState() operation returns a PNSetStateResult? which contains the following operations:

MethodTypeDescription
stateByUUIDMap<String, JsonElement>Map of UUIDs and the user states.

Other Examples

Set state for channels in channel group

pubnub.setPresenceState(
channels = listOf("ch1", "ch2", "ch3"), // apply on those channels
channelGroups = listOf("cg1", "cg2", "cg3"), // apply on those channel groups
state = JsonObject().apply { addProperty("is_typing", true) }
).async { result ->}
if (!status.error) {
result!!.state // {"data":{"isTyping":true}}
} else {
// handle error
status.exception?.printStackTrace()
}

Get state for UUID

pubnub.getPresenceState(
channels = listOf("ch1", "ch2"), // channels to fetch state for
uuid = "such_uuid" // uuid of user to fetch, or own uuid by default
).async { result ->
result.onFailure { exception ->
exception.printStackTrace()
}.onSuccess { value ->
value!!.stateByUUID.forEach { (channel, state) ->
println("Channel: $channel, state: $state")
}
}
}
Last updated on