Publish/Subscribe 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.

The foundation of PubNub is the ability to send and deliver a message in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.

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

Publish

icon

Available in entities

Channel

publish() sends a message to all channel subscribers. A successfully published message is replicated across PubNub's points of presence and sent simultaneously to all subscribed clients on a channel.

  • You must initialize PubNub with the publishKey.
  • You must create a Channel entity

    Entity

    A subscribable object within a PubNub SDK that allows you to perform context-specific operations.
    where you will publish to.
  • You don't have to be subscribed to a channel to publish to it.
  • You cannot publish to multiple channels simultaneously.

Method(s)

To publish to a channel, you must first create a Channel entity where you provide the name of the channel you want to publish to.

val channel = pubnub.channel("channelName")

channel.publish(
message: Any,
shouldStore: Boolean,
meta: Any,
queryParam: Map<String, String>,
usePost: Boolean,
ttl: Integer,
customMessageType: String
).async { result -> /* check result */ }
ParameterTypeRequiredDefaultDescription
messageAnyYesThe payload
shouldStoreBooleanOptionalaccount defaultStore message in history.
If not specified, the decision depends on whether Message Persistence has been enabled for the key or not.
metaAnyOptionalNot setMetadata object which can be used with the filtering ability.
queryParamMap<String, String>OptionalNot setOne or more query parameters to be passed to the server, for analytics purposes.
Overridden in case of conflicts with reserved PubNub parameters, such as UUID or instance_id. Accessible from the Admin Portal, and never returned in server responses.
usePostBooleanOptionalfalseUse HTTP POST to publish.
ttlIntegerOptionalSet a per message time to live in Message Persistence.
1. If shouldStore = true, and ttl = 0, the message is stored with no expiry time.
2. If shouldStore = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
3. If shouldStore = false, the ttl parameter is ignored.
4. If ttl isn't specified, then expiration of the message defaults back to the expiry value for the key.
customMessageTypeStringNoA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.

Basic Usage

val configBuilder = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}
val pubnub = PubNub.create(configBuilder.build())

val channel = pubnub.channel("myChannel")

val myMessage = JsonObject().apply {
addProperty("lat", 32L)
addProperty("lng", 32L)
}

channel.publish(
message = myMessage,
customMessageType = "text-message"
show all 23 lines
Subscribe to the channel

Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.

Response

The publish() operation returns a PNPublishResult?:

ParameterTypeDescription
timetokenLongReturns a Long representation of the timetoken when the message was published.

Other Examples

Publish with metadata

val configBuilder = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}
val pubnub = PubNub.create(configBuilder.build())

val channel = pubnub.channel("myChannel")

val myMessage = JsonObject().apply {
addProperty("text", "Hello, world")
}

channel.publish(
message = myMessage,
meta = mapOf("lang" to "en"),
usePost = true,
show all 24 lines

Publishing JsonArray (Google GSON)

val configBuilder = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}
val pubnub = PubNub.create(configBuilder.build())

val channel = pubnub.channel("myChannel")

val myMessage = JsonArray().apply {
add(32L)
add(35L)
}

channel.publish(
message = myMessage,
customMessageType = "text-message"
show all 23 lines

Publishing JSONObject (org.json)

val configBuilder = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}
val pubnub = PubNub.create(configBuilder.build())

val channel = pubnub.channel("myChannel")

val myMessage = JSONObject().apply {
put("lat", 32L)
put("lng", 32L)
}

channel.publish(
message = myMessage,
customMessageType = "text-message"
show all 23 lines

Publishing JSONArray (org.json)

val configBuilder = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}

val pubnub = PubNub.create(configBuilder.build())

val channel = pubnub.channel("myChannel")

val myMessage = JSONArray().apply {
put(32L)
put(33L)
}

channel.publish(
message = myMessage,
show all 24 lines

Store the published message for 10 hours

val configBuilder = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}

val pubnub = PubNub.create(configBuilder.build())

val channel = pubnub.channel("myChannel")

val myMessage = JsonObject().apply {
addProperty("text", "Hello, world")
}

channel.publish(
message = myMessage,
shouldStore = true,
show all 25 lines

Fire

icon

Available in entities

Channel

The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler.

  • You must initialize PubNub with the publishKey.
  • You must create a Channel entity where you will fire to.
  • The message sent via fire() isn't replicated and won't be received by subscribers.
  • The message is not stored in history.

Method(s)

To fire to a channel, you must first create a Channel entity where you provide the name of the channel you want to fire to.

val channel = pubnub.channel("channelName")

channel.fire(
message: Any,
meta: Any,
usePost: Boolean,
).async { result -> /* check result */ }
ParameterTypeRequiredDefaultDescription
messageAnyYesThe payload
metaAnyOptionalNot setMetadata object which can be used with the filtering ability
usePostBooleanOptionalfalseUse POST to fire

Basic Usage

val config = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}

val channel = pubnub.channel("myChannel")

channel.fire(myMessage).async { result ->
result.onFailure { exception ->
println("Error while publishing")
exception.printStackTrace()
}.onSuccess { value ->
println("Message sent, timetoken: ${value.timetoken}")
}
}

Response

The fire() operation returns a PNPublishResult?:

ParameterTypeDescription
timetokenLongReturns a Long representation of the timetoken when the message was published.

Signal

icon

Available in entities

Channel

The signal() function is used to send a signal

Signal

A non-persistent message limited to 64 bytes designed for high-volume usecases where the the most recent data is relevant, like GPS location updates.
to all subscribers of a channel.

  • You must initialize PubNub with the publishKey.
  • You must create a Channel entity where you will fire to.
  • The message payload size (without the URI or headers) is limited to 64 bytes. If you require a larger payload size, contact support.

Method(s)

val channel = pubnub.channel("myChannel")

channel.signal(
message: Any,
customMessageType: String
).async { result -> }
ParameterTypeRequiredDefaultDescription
messageAnyYesThe payload
customMessageTypeStringNoA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.

Basic Usage

val config = com.pubnub.api.v2.PNConfiguration.builder(UserId("myUserId"), "demo").apply {
publishKey = "demo"
}

val channel = pubnub.channel("myChannel")

channel.signal(
message = "This is a signal!",
customMessageType = "text-message"
).async() { result ->
result.onFailure { exception ->
println("Error while publishing")
exception.printStackTrace()
}.onSuccess { value ->
println("Signal sent, timetoken: ${value.timetoken}, ${value.toString()}")
show all 17 lines

Response

The signal() operation returns a PNPublishResult?:

MethodTypeDescription
timetokenLongReturns a Long representation of the timetoken when the signal was published.

Subscribe

The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified entity or set of entities. To subscribe successfully, you must configure the appropriate subscribeKey at initialization.

Entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific entity:

A newly subscribed client receives messages after the subscribe() call completes. You can configure retryConfiguration to automatically attempt to reconnect if a client gets disconnected.

Subscription scope

Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:

  • Subscription, created from an entity with a scope of only that entity (for example, a particular channel)
  • SubscriptionSet, created from the PubNub client with a global scope (for example, all subscriptions created on a single pubnub object ). A subscription set can have one or more subscriptions.

The event listener is a single point through which your app receives all the messages, signals, and events in the entities you subscribed to. For information on adding event listeners, refer to Event listeners.

Create a subscription

Managing subscription lifecycle

The Subscription object implements the AutoCloseable interface to help you release resources by unsubscribing and removing all listeners. Always call Subscription.close() when you no longer need this Subscription.

An entity-level Subscription allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscriptions is useful for handling various message/event types differently in each channel.

// Entity-based, local-scoped

// Specify the channel for subscription
val myChannel = pubnub.channel("channelName")

// Create subscription options, if any
val options = SubscriptionOptions.receivePresenceEvents()

// Return a Subscription object that is used to establish the subscription
val subscription = myChannel.subscription(options)

// Activate the subscription to start receiving events
subscription.subscribe()
ParameterTypeRequiredDescription
optionsSubscriptionOptionsNoSubscription behavior configuration. Use null for no specific options.

Create a subscription set

Managing subscription lifecycle

The SubscriptionSet object implements the AutoCloseable interface to help you release resources by unsubscribing and removing all listeners. Always call SubscriptionSet.close() when you no longer need this SubscriptionSet.

A client-level SubscriptionSet allows you to receive messages and events for all entities in the set. A single SubscriptionSet is useful for similarly handling various message/event types in each channel.

// client-based, general-scoped

pubnub.subscriptionSetOf(
channels: Set<String>,
channelGroups: Set<String>,
options: SubscriptionOptions
)
ParameterTypeRequiredDescription
 → channelsSet<String>NoSet of channel names to subscribe to. Use an empty set for no channels.
 → channelGroupsSet<String>NoSet of channel group names to subscribe to. Use an empty set for no channel groups.
 → optionsSubscriptionOptionsNoAdditional subscription configuration to define the subscription behavior. If you don't set any options, EmptyOptions is used by default.
Add/remove sets

You can add and remove subscription sets to create new sets. Refer to the Other examples section for more information.

SubscriptionOptions

SubscriptionOptions is a class designed to configure subscription behaviors with optional modifiers. When no specific options are required, EmptyOptions is set by default.

The class includes:

OptionDescription
receivePresenceEvents()Enables receiving presence events for the subscription. It's not required and should be included only when presence information is needed.
filter(predicate: (PNEvent) -> Boolean)Allows for custom filtering of events delivered to the subscription based on the provided predicate. Useful for event-specific handling.

Method(s)

Subscription and SubscriptionSet use the same methods to subscribe:

Subscribe

To subscribe, you can use the following method:

// For subscription
subscription.subscribe()
// For subscription set
subscriptionSet.subscribe()
Basic usage
// Step 1: Create a subscription set
val subscriptionSet = pubnub.subscriptionSetOf(
// Specify channels with default options
channels = setOf("my_channel", "other_channel"),
)

// Step 2: Subscribe using the subscription set
subscriptionSet.subscribe()
Other examples
Create a subscription set from 2 individual subscriptions
// Create subscriptions
val subscription1 = pubnub.channel("channelName").subscription()
val subscription2 = pubnub.channelGroup("channelGroup").subscription()

// Combine into a subscription set
val subscriptionSet = subscription1 + subscription2

// Add another subscription to the set
subscriptionSet += subscription3
// Or
subscriptionSet.add(subscription3)

// Remove a subscription from the set
subscriptionSet -= subscription3
// Or
show all 16 lines
Returns

The subscribe() method doesn't have a return value.

Subscribe with timetoken

Impact on other subscriptions

Subscribing with a timetoken affects all other subscriptions because it overwrites the timetoken in the single PubNub server connection in the SDK. However, those other subscriptions will not deliver messages older than ones that were already delivered - after receiving an event, a subscription only gets future events, ignoring those before or at the time of the last event received.

To subscribe to real-time updates from a given timetoken, use the following method:

subscriptionSet.subscribe(SubscriptionCursor(timetoken = yourTimeToken))
ParameterTypeRequiredDescription
cursorSubscriptionCursorYesCursor from which to return any available cached messages. SubscriptionCursor would typically include a timetoken (long integer) representing the point in time from which to receive updates.
Basic usage
// Define the channels to subscribe to
val channels = setOf("my_channel", "other_channel")

// Create a subscription set with specified channels and subscription options
val subscriptionSet = pubnub.subscriptionSetOf(channels, options)

// Define the timetoken for where the subscription should start
val yourTimeToken = 100000000000L // Directly using Long type

// Subscribe to the created SubscriptionSet with the desired timetoken
subscriptionSet.subscribe(SubscriptionCursor(timetoken = yourTimeToken))
Returns

The method for subscribing with a timetoken doesn't have a return value.

Event listeners

Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.

You can attach listeners to the instances of Subscription, SubscriptionSet, and, in the case of the connection status, the PubNub client.

Add listeners

You can add listeners for various types of updates related to your subscription. You can implement listeners for general updates (that handle multiple event types at once) or choose listeners dedicated to specific event types such as Message or File.

Handle multiple event types

Method(s)
fun addListener(listener: EventListener)
Basic usage
// Create a subscription to a specific channel
val subscription = pubnub.channel("my_channel").subscription()

// Add a listener to the subscription for handling various event types
subscription.addListener(object : EventListener {
override fun message(pubnub: PubNub, message: PNMessageResult) {
// Log or process message
println("Message: ${message.message}")
}

override fun signal(pubnub: PubNub, signal: PNSignalResult) {
// Handle signals
println("Signal: ${signal.message}")
}

show all 57 lines

Handle one event type

Method(s)

You can also directly register listeners for specific event types on the subscription object by assigning lambda expressions. This method allows you to handle events such as messages, signals, message actions, files, objects, and presence.

Using this method, you cannot have multiple listeners attached to the same event type. Assigning a new listener with this method overwrites the previous one.

Basic usage
subscription.onMessage = { message ->
/* Handle message */
}

subscription.onSignal = { signal ->
/* Handle signal */
}

subscription.onMessageAction = { messageAction ->
/* Handle message action */
}

subscription.onFile = { file ->
/* Handle file event */
}
show all 23 lines
Remove event listener

To remove the listener for a specific event, assign null to it.

subscription.onMessage = null

Add connection status listener

Use the StatusListener interface with your PubNub instance to add a listener dedicated to connection status updates.

Client scope

This listener is only available on the PubNub object.

Method(s)

pubnub.addListener(object : StatusListener() {
override fun status(pubnub: PubNub, status: PNStatus) {
// Handle connection status updates
println("Connection Status: ${status.category}")
}
})

Basic usage

// Adding the status listener to the PubNub client
pubnub.addListener(object : StatusListener() {
override fun status(pubnub: PubNub, status: PNStatus) {
// This block is executed asynchronously for each status update
println("Connection Status: ${status.category}")
}
})

Returns

This method returns the subscription status and will emit various statuses depending on your client network connection.

To help you adjust your app code, see the Status Events for Subscribe for the exact mapping between the current and deprecated Kotlin SDK statuses.

For more generic information, head to SDK Connection Lifecycle.

Unsubscribe

Stop receiving real-time updates from a Subscription or a SubscriptionSet.

Method(s)

// For subscription
subscription.unsubscribe()
// For subscription set
subscriptionSet.unsubscribe()

Basic Usage

// Subscribe to a channel
subscription.subscribe()

// Unsubscribe from that channel
subscription.unsubscribe()

Returns

None

Unsubscribe All

Stop receiving real-time updates from all listeners and remove the entities associated with them.

Client scope

This method is only available on the PubNub object.

Method(s)

pubnub.unsubscribeAll()

Basic Usage

// Subscribe to channels
pubnub.subscribe(channels = setOf("my_channel", "other_channel"))

// Subscribe to a channel group
pubnub.subscribe(channelGroups = setOf("my_channel_group"))

// Later, when you want to unsubscribe from all subscriptions
pubnub.unsubscribeAll()

Returns

None

Publish (deprecated)

The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.

Publish Anytime

It's not required to be subscribed to a channel in order to publish to that channel.

Message Data

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data should not contain special classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

Don't JSON serialize

It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead, just pass the full object as the message payload. PubNub takes care of everything for you.

Message Size

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details, check the support article.

Message Publish Rate

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to Multiple Channels

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing Messages Reliably

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (not concurrently).
  • Check that the return code is success (for example, [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs, for example, Publish no faster than 5 msgs per second to any one channel.

Method(s)

To Publish a message you can use the following method(s) in the Kotlin SDK:

pubnub.publish(
message: Any,
channel: String,
shouldStore: Boolean,
meta: Any,
queryParam: Map<String, String>,
usePost: Boolean,
ttl: Integer
).async { result -> /* check result */ }
ParameterTypeRequiredDefaultDescription
messageAnyYesThe payload
channelStringYesDestination of the message
shouldStoreBooleanOptionalaccount defaultStore message in history.
If not specified, the decision depends on whether Message Persistence has been enabled for the key or not.
metaAnyOptionalNot setMetadata object which can be used with the filtering ability.
queryParamMap<String, String>OptionalNot setOne or more query parameters to be passed to the server, for analytics purposes.
Overridden in case of conflicts with reserved PubNub parameters, such as UUID or instance_id. Accessible from the Admin Portal, and never returned in server responses.
usePostBooleanOptionalfalseUse HTTP POST to publish.
ttlIntegerOptionalSet a per message time to live in Message Persistence.
1. If shouldStore = true, and ttl = 0, the message is stored with no expiry time.
2. If shouldStore = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
3. If shouldStore = false, the ttl parameter is ignored.
4. If ttl isn't specified, then expiration of the message defaults back to the expiry value for the key.

Basic Usage

Publish a message to a channel:

pubnub.publish(
message = JsonObject().apply {
addProperty("lat", 32L)
addProperty("lng", 32L)
},
channel = "my_channel"
).async { result ->
result.onSuccess { value ->
println("Publish timetoken ${value.timetoken}")
}
}
Subscribe to the channel

Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.

Returns

The publish() operation returns a PNPublishResult? which contains the following operations:

MethodTypeDescription
timetokenLongReturns a Long representation of the timetoken when the message was published.

Other Examples

Publish with metadata
pubnub.publish(
message = mapOf("hello" to "there"),
channel = "my_channel",
shouldStore = true,
meta = mapOf("lang" to "en"),
usePost = true
).async { result -> /* check result */ }
Publishing JsonObject (Google GSON)
pubnub.publish(
message = JsonObject().apply {
addProperty("lat", 32L)
addProperty("lng", 32L)
},
channel = "my_channel"
).async { result -> /* check result */ }
Publishing JsonArray (Google GSON)
pubnub.publish(
message = JsonArray().apply {
add(32L)
add(35L)
},
channel = "my_channel"
).async { result -> /* check result */ }
Publishing JSONObject (org.json)
pubnub.publish(
message = JSONObject().apply {
put("lat", 32L)
put("lng", 32L)
},
channel = "my_channel"
).async { result -> /* check result */ }
Publishing JSONArray (org.json)
pubnub.publish(
message = JSONArray().apply {
put(32L)
put(33L)
},
channel = "my_channel"
).async { result -> /* check result */ }
Store the published message for 10 hours
pubnub.publish(
message = "test",
channel = "my_channel",
shouldStore = true,
ttl = 10
).async { result -> /* check result */ }

Fire (deprecated)

The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.

Method(s)

To Fire a message you can use the following method(s) in the Kotlin SDK:

pubnub.fire(
message: Any,
channel: String,
meta: Any,
usePost: Boolean
).async { result -> /* check result */ }
ParameterTypeRequiredDefaultDescription
messageAnyYesThe payload
channelStringYesDestination of the message
metaAnyOptionalNot setMetadata object which can be used with the filtering ability
usePostBooleanOptionalfalseUse POST to publish

Basic Usage

Fire a message to a channel:

pubnub.fire(
message = listOf("hello", "there"),
channel = "my_channel"
).async { result ->
result.onFailure { exception ->
// Handle error
}.onSuccess { value ->
// Handle successful method result
}
}

Signal (deprecated)

The signal() function is used to send a signal to all subscribers of a channel.

By default, signals are limited to a message payload size of 64 bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.

Method(s)

To Signal a message you can use the following method(s) in the Kotlin SDK:

pubnub.signal(
message: Any,
channel: String
).async { result -> }
ParameterTypeRequiredDefaultDescription
messageAnyYesThe payload
channelStringYesDestination of the message

Basic Usage

Signal a message to a channel:

pubnub.signal(
message = "hello",
channel = "my_channel"
).async { result ->
result.onFailure { exception ->
// Handle error
}.onSuccess { value ->
// Handle successful method result
}
}

Response

The signal() operation returns a PNPublishResult? which contains the following operations:

MethodTypeDescription
timetokenLongReturns a Long representation of the timetoken when the signal was published.

Subscribe (deprecated)

Deprecated

This method is deprecated. Use Subscribe instead.

Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the Event Listeners section.

Description

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribeKey at initialization.

By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes. If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period. This can be achieved by setting setReconnectionPolicy to PNReconnectionPolicy.LINEAR, when initializing the client.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Subscribe to a channel you can use the following method(s) in the Kotlin SDK:

pubnub.subscribe(
channels: List<String>,
channelGroups: List<String>,
withTimetoken: Long,
withPresence: Boolean
)
ParameterTypeRequiredDescription
channelsList<String>OptionalSubscribe to channels. Either channel or channelGroup is required.
channelGroupsList<String>OptionalSubscribe to channelGroups. Either channel or channelGroup is required.
withTimetokenLongOptionalPass a timetoken.
withPresenceBooleanOptionalAlso subscribe to related presence information.

Basic Usage

Subscribe to a channel:

pubnub.subscribe(
channels = listOf("my_channel")
)
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Returns

PNMessageResult

PNMessageResult is returned in the Listeners.

The subscribe() operation returns a PNStatus which contains the following operations:

MethodTypeDescriptions
categoryPNStatusCategoryDetails of PNStatusCategory are here.
errorBooleanIs true in case of an error

The subscribe() operation returns a PNMessageResult for messages which contains the following operations:

MethodTypeDescriptions
messageJsonElementThe message sent on the channel
subscriptionString?The channel group or wildcard subscription match (if exists).
channelStringThe channel for which the message belongs
timetokenLong?Timetoken for the message
userMetadataJsonElement?User metadata

The subscribe() operation returns a PNPresenceEventResult for presence which contains the following operations:

MethodTypeDescriptions
eventStringEvents like join, leave, timeout, state-change, interval.
uuidStringUUID for the event
timestampLongTimestamp for the event
occupancyIntCurrent occupancy
stateJsonElement?State of the UUID
subscriptionStringThe channel group or wildcard subscription match (if exists)
channelStringThe channel of which the message belongs
timetokenLongTimetoken of the message
userMetadataAnyUser metadata

The subscribe() operation returns a PNSignalResult for signals which contains the following operations:

MethodTypeDescriptions
messageJsonElementThe signal sent on the channel
subscriptionStringThe channel group or wildcard subscription match (if exists)
channelStringThe channel of which the message belongs
timetokenLongTimetoken of the message
userMetadataAnyUser metadata

Other Examples

Basic subscribe with logging
val pnConfiguration = PNConfiguration().apply {
subscribeKey = "my_subkey"
publishKey = "my_pubkey"
logVerbosity = PNLogVerbosity.BODY
}

val pubnub = PubNub.create(pnConfiguration)

pubnub.subscribe(
channels = listOf("my_channel")
)

Subscribing to multiple channels

It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.

Alternative subscription methods

You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.

pubnub.subscribe(
channels = listOf("ch1", "ch2") // subscribe to channels information
)
Subscribing to a Presence channel
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.

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres. Presence data can be observed inside the SubscribeCallback#presence(PubNub, PNPresenceResult) callback.

pubnub.subscribe(
channels = listOf("my_channel"), // subscribe to channels
withPresence = true // also subscribe to related presence information
)

Sample Responses

Join Event
if (presence.event == "join") {
presence.uuid // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.timestamp // 1345546797
presence.occupancy // # users in channel
}
Leave Event
if (presence.event == "leave") {
presence.uuid // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.timestamp // 1345546797
presence.occupancy // # users in channel
}
Timeout Event
if (presence.event == "timeout") {
presence.uuid // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.timestamp // 1345546797
presence.occupancy // # users in channel
}
Custom Presence Event (State Change)
if (presence.event == "state-change") {
presence.uuid // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.timestamp // 1345546797
presence.occupancy // # users in channel
presence.state?.asJsonObject // {"data":{"isTyping":true}}
}
Interval Event
if (presence.event == "interval") {
presence.uuid // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.timestamp // 1345546797
presence.occupancy // # users in channel
}

When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message. This settings can be altered in the Admin Portal.

  • joined
  • left
  • timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

if (presence.event == "interval") {
presence.timestamp // 1345546797
presence.occupancy // # users in channel
presence.join // ["uuid1", "uuid2"]
presence.timeout // ["uuid3"]
}

If the full interval message is greater than 30KiB (since the max publish payload is ∼32KiB), none of the extra fields will be present. Instead, there will be a here_now_refresh Boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

if (presence.event == "interval") {
presence.timestamp // 1345546797
presence.occupancy // # users in channel
presence.hereNowRefresh // true
}

Wildcard subscribe to channels
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).

pubnub.subscribe(
channels = listOf("foo.*") // subscribe to channels information
)
Wildcard grants and revokes

Only one level (a.*) of wildcarding is supported. If you grant on * or a.b.*, the grant will treat * or a.b.* as a single channel named either * or a.b.*. The same rule applies to revokes - you can revoke permissions with wildcards from one level deep, like a.*. However, you can do that only if you initially used wildcards to grant permissions to a.*.

Subscribing with 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.

Required UUID

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 = "demo"
publishKey = "demo"
}

class ComplexData(
val fieldA: String,
val fieldB: Int
)

val pubnub = PubNub.create(pnConfiguration)

pubnub.addListener(object : SubscribeCallback() {
override fun status(pubnub: PubNub, status: PNStatus) {
if (status.category == PNStatusCategory.PNConnectedCategory) {
show all 29 lines
Subscribe to a channel group
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.

pubnub.subscribe(
channels = listOf("ch1", "ch2"), // subscribe to channels
channelGroups = listOf("cg1", "cg2"), // subscribe to channel groups
withTimetoken = 1337L, // optional, pass a timetoken
withPresence = true // also subscribe to related presence information
)
Subscribe to the presence channel of a channel group
note
Requires Stream Controller and Presence add-ons

This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.subscribe(
channelGroups = listOf("cg1", "cg2"), // subscribe to channel groups
withTimetoken = 1337L, // optional, pass a timetoken
withPresence = true // also subscribe to related presence information
)

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 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}")
show all 61 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 with the retryConfiguration parameter.

Listeners status events

Refer to Status Events for Subscribe for details.

Unsubscribe (deprecated)

Deprecated

This method is deprecated. Use Unsubscribe instead.

When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Unsubscribe from a channel you can use the following method(s) in the Kotlin SDK:

pubnub.unsubscribe(
channels: List<String>,
channelGroups: List<String>
)
ParameterTypeRequiredDescription
channelsList<String>OptionalUnsubscribe from channels. Either channel or channelGroup is required.
channelGroupsList<String>OptionalUnsubscribe from channelGroups. Either channel or channelGroup is required`.

Basic Usage

Unsubscribe from a channel:

pubnub.unsubscribe(
channels = listOf("my_channel") // subscribe to channel groups
)
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Response

The output below demonstrates the response to a successful call:

override fun presence(pubnub: PubNub, presence: PNPresenceEventResult) {
if (presence.event == "leave") {
presence.timestamp // 1345546797
presence.occupancy // 2
presence.uuid // left_uuid
}
}

Other Examples

Unsubscribing from multiple channels
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.

pubnub.unsubscribe(
channels = listOf("ch1", "ch2", "ch3"),
channelGroups = listOf("cg1", "cg2", "cg3")
)

Example response:

override fun presence(pubnub: PubNub, presence: PNPresenceEventResult) {
if (presence.event == "leave") {
presence.timestamp // 1345546797
presence.occupancy // 2
presence.uuid // left_uuid
}
}
Unsubscribing from a channel group
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.

pubnub.unsubscribe(
channelGroups = listOf("cg1", "cg2", "cg3")
)

Example response:

override fun presence(pubnub: PubNub, presence: PNPresenceEventResult) {
if (presence.event == "leave") {
presence.timestamp // 1345546797
presence.occupancy // 2
presence.uuid // left_uuid
}
}
Last updated on