Presence 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.
Presence lets you track who is online or offline and store custom state information. Presence shows:
- When a user has joined or left a channel
- How many users are subscribed to a particular channel (occupancy)
- Which channels a user or device is subscribed to
- Presence state associated with these users
Learn more about our Presence feature in the Presence overview.
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}
Here now
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
This method returns information about the current state of a channel, including a list of unique user IDs (universally unique identifiers, UUIDs) currently subscribed to the channel and the total occupancy count of the channel.
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:
1pubnub.hereNow(
2 channels: List<String>,
3 channelGroups: List<String>,
4 includeState: Boolean,
5 includeUUIDs: Boolean,
6 limit: Int,
7 offset: Int?
8).async { result -> }
| Parameter | Description |
|---|---|
channelsType: List<String>Default: emptyList() | The channels to get the 'here now' details of. |
channelGroupsType: List<String>Default: emptyList() | The channelGroups to get the 'here now' details of. Wildcards are not supported. |
includeStateType: BooleanDefault: false | If true, the response will include the presence states of the users for channels/channelGroups. |
includeUUIDsType: BooleanDefault: true | If true, the response will include the UUIDs of the connected clients. |
limitType: IntDefault: 1000 | Maximum number of occupants to return per channel. Valid range: 0-1000. The server enforces the maximum of 1000 and rejects values outside this range. Use 0 to get occupancy counts without user details (when limit=0, the server omits UUIDs entirely). |
offsetType: Int?Default: null | Zero-based starting index for pagination. Returns occupants starting from this position in the list. Must be >= 0. Requires limit > 0. Server rejects negative values. Use with limit to paginate through large occupant lists. |
Sample code
Reference code
Get a list of UUIDs subscribed to channel
1
Returns
The hereNow() operation returns a PNHereNowResult? which contains the following operations:
| Method | Description |
|---|---|
totalChannelsType: Int | Total channels |
totalOccupancyType: Int | Total occupancy |
channelsType: Map<String, PNHereNowChannelData> | A map with values of PNHereNowChannelData for each channel. See PNHereNowChannelData for more details. |
PNHereNowChannelData
| Method | Description |
|---|---|
channelNameType: String | Channel name |
occupancyType: Int | Occupancy of the channel |
occupantsType: List<PNHereNowOccupantData> | A list of PNHereNowOccupantData, see PNHereNowOccupantData for more details. |
PNHereNowOccupantData
| Method | Description |
|---|---|
uuidType: String | UUID of the user |
stateType: JsonElement? | State of the user |
Other examples
Returning state
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
1
Example response:
1.async { result: Result<PNHereNowResult> ->
2 result.onSuccess { res: PNHereNowResult ->
3 res.channels.values.forEach { channelData ->
4 channelData.channelName // ch1
5 channelData.occupancy // 3
6 channelData.occupants.forEach { o ->
7 o.uuid // some_uuid, returned by default
8 o.state // {"data":{"isTyping":true}}, requested
9 }
10 }
11 }.onFailure { e ->
12 // handle error
13 e.message
14 e.statusCode
15 e.pubnubError
show all 17 linesReturn occupancy only
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
You can return only the occupancy information for a single channel by specifying the channel and setting UUIDs to false:
1
Example response:
1.async { result: Result<PNHereNowResult> ->
2 result.onSuccess { res: PNHereNowResult ->
3 res.channels.values.forEach { channelData ->
4 channelData.channelName // ch1
5 channelData.occupancy // 3
6 }
7 }.onFailure { e ->
8 // handle error
9 e.message
10 e.statusCode
11 e.pubnubError
12 }
13}
Here now for channel groups
1
Example response:
1.async { result: Result<PNHereNowResult> ->
2 result.onSuccess { res: PNHereNowResult ->
3 res.totalOccupancy
4 }.onFailure { e ->
5 // handle error
6 e.message
7 e.statusCode
8 e.pubnubError
9 }
10}
Where now
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
This method returns the list of channels a UUID is subscribed to.
Timeout events
If the app restarts (or the page refreshes) 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:
1pubnub.whereNow(
2 uuid: String
3).async { result -> }
| Parameter | Description |
|---|---|
uuidType: StringDefault: n/a | UUID of the user to get its current channel subscriptions. |
Sample code
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
1
Returns
The whereNow() operation returns a PNWhereNowResult? which contains the following operations:
| Method | Description |
|---|---|
channelsType: List<String> | List of channels where the uuid is present. |
Other examples
Obtain information about the current list of channels of some other UUID
1
User state
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
Clients can set a dynamic custom state (score, game state, location) for their users on one or more channels and store it on a channel as long as the user stays subscribed.
The state is not persisted, and when the client disconnects, the state data is lost. For more information, refer to Presence State.
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
1pubnub.setPresenceState(
2 channels: List<String>,
3 channelGroups: List<String>,
4 state: Any,
5 uuid: String
6).async { result -> }
| Parameter | Description |
|---|---|
channelsType: List<String>Default: n/a | Channels to set state to. |
channelGroupsType: List<String>Default: n/a | Channel groups to set state to. |
stateType: AnyDefault: n/a | The state to set. |
uuidType: StringDefault: n/a | The UUID to set state for. |
Get state
1pubnub.getPresenceState(
2 channels: List<String>,
3 channelGroups: List<String>,
4 uuid: String
5).async { result -> }
To get the state, call getPresenceState() you can use the following method(s) in the Kotlin SDK:
| Parameter | Description |
|---|---|
channelsType: List<String>Default: n/a | Channels to get state of. |
channelGroupsType: List<String>Default: n/a | Channel groups to get state of. |
uuidType: StringDefault: n/a | The UUID to get state for. |
Sample code
1
Returns
The setPresenceState() operation returns a PNSetStateResult? which contains the following operations:
| Method | Description |
|---|---|
stateType: JsonElement | The actual state object |
The getPresenceState() operation returns a PNSetStateResult? which contains the following operations:
| Method | Description |
|---|---|
stateByUUIDType: Map<String, JsonElement> | Map of UUIDs and the user states. |
Other examples
Set state for channels in channel group
1
Get state for UUID
1