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

PubNub's publish-processing latency, the time to accept and acknowledge a publish request, is about 0.5 ms within the same region. Send a message to one recipient or broadcast to thousands of subscribers.

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

Publish​

icon

Available in SDK entities

Channel

publish() sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.

  • You must initialize PubNub with the publishKey.
  • You must create a Channel SDK entity 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 SDK entity where you provide the name of the channel you want to publish to.

1Channel channel = pubnub.channel("myChannel");
2
3channel.publish(Object message)
4 .shouldStore(Boolean)
5 .meta(Object)
6 .queryParam(HashMap)
7 .usePOST(Boolean)
8 .ttl(Integer);
9 .customMessageType(String)
* required
ParameterDescription
message *
Type: Object
Default:
n/a
The payload.
shouldStore
Type: Boolean
Default:
account default
Store in history.
If shouldStore is not specified, then the history configuration on the key is used.
meta
Type: Object
Default:
Not set
Meta data object which can be used with the filtering ability.
queryParam
Type: HashMap<string,string>
Default:
Not set
One 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 your PubNub Dashboard, and never returned in server responses.
usePOST
Type: Boolean
Default:
false
Use POST to publish.
ttl
Type: Integer
Default:
n/a
Set 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 unless you have message retention set to Unlimited on your keyset configuration in the Admin Portal.
  3. If shouldStore = false, the ttl parameter is ignored.
  4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
customMessageType
Type: String
Default:
n/a
A 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.
sync
Type: Command
Default:
n/a
Block the thread, exception thrown if something goes wrong.
async
Type: Consumer<Result>
Default:
n/a
Consumer of a Result of type PNPublishResult

Sample code​

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.

Publish a message to a channel​

1

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.

Other examples​

Publish with metadata​

1

Publishing JsonObject (Google GSON)​

1

Publishing JsonArray (Google GSON)​

1

Publishing JSONObject (org.json)​

1

Publishing JSONArray (org.json)​

1

Store the published message for 10 hours​

1

Response​

The publish() operation returns a PNPublishResult:

MethodDescription
getTimetoken()
Type: Long
Returns a long representation of the timetoken when the signal was published.

Fire​

icon

Available in SDK entities

Channel

The fire endpoint sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire() aren't replicated to subscribers and aren't stored in history.

  • You must initialize PubNub with the publishKey.
  • You must create a Channel SDK 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)​

1Channel channel = pubnub.channel("myChannel");
2
3channel.fire(Object message)
4 .meta(Object)
5 .usePOST(Boolean);
* required
ParameterDescription
message *
Type: Object
Default:
n/a
The payload.
meta
Type: Object
Default:
Not set
Meta data object which can be used with the filtering ability.
usePOST
Type: Boolean
Default:
false
Use POST to publish.
sync
Type: Command
Default:
n/a
Block the thread, exception thrown if something goes wrong.
async
Type: Consumer<Result>
Default:
n/a
Consumer of a Result of type PNPublishResult

Sample code​

1

Response​

The fire() operation returns a PNPublishResult:

MethodDescription
getTimetoken()
Type: Long
Returns a long representation of the timetoken when the signal was published.

Signal​

icon

Available in SDK entities

Channel

The signal() function sends a signal to all subscribers of a channel.

  • You must initialize PubNub with the publishKey.
  • You must create a Channel SDK 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)​

1Channel channel = pubnub.channel("myChannel");
2
3channel.signal(Object message)
4 .customMessageType(String);
* required
ParameterDescription
message *
Type: Object
The payload which will be serialized and sent.
customMessageType
Type: String
A 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.
sync
Type: PNPublishResult
Executes the call. Blocks the thread, exception is thrown if something goes wrong.
async
Type: Consumer<Result>
Executes the call asynchronously.

Sample code​

1

Response​

The signal() operation returns a PNPublishResult:

MethodDescription
getTimetoken()
Type: Long
Returns a long representation of the timetoken when the signal was published.

Subscribe​

Subscribe opens a TCP socket and listens for messages and events on a specified SDK entity or set of SDK entities. Set subscribeKey during initialization.

Conceptual overview

For more general information about subscriptions, refer to Subscriptions.

SDK entities are first-class citizens that expose their APIs. You can subscribe using the PubNub client or directly on a specific SDK entity:

After subscribe(), the client receives new messages. Configure retryConfiguration to reconnect automatically after disconnects.

Subscription scope​

Subscriptions let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:

  • Subscription: created from an SDK entity and scoped to that SDK entity (for example, a particular channel)
  • SubscriptionSet: created from the PubNub client and scoped to the client (for example, all subscriptions created on a single pubnub object). A set can include one or more subscriptions.

One event listener receives all messages, signals, and events for the SDK entities you subscribe to. To add listeners, see 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 SDK-entity-level Subscription allows you to receive messages and events for only that SDK entity for which it was created. Using multiple SDK-entity-level Subscriptions is useful for handling various message/event types differently in each channel.

1// SDK entity-based, local-scoped
2
3channel.subscription(SubscriptionOptions options)
* required
ParameterDescription
options
Type: SubscriptionOptions
Subscription behavior configuration. Use null for no specific options.

Sample code​

1

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 SDK entities in the set. A single SubscriptionSet is useful for similarly handling various message/event types in each channel.

1// client-based, general-scoped
2
3pubnub.subscriptionSetOf(
4 Set<String> channels,
5 Set<String> channelGroups,
6 SubscriptionOptions options
7)
* required
ParameterDescription
> channels
Type: Set<String>
Set of channel names to subscribe to. Use an empty set for no channels.
> channelGroups
Type: Set<String>
Set of channel group names to subscribe to. Use an empty set for no channel groups.
> options
Type: SubscriptionOptions
Additional 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()Whether presence updates for userIds should be delivered through the listener streams.

For information on how to receive presence events and what those events are, refer to Presence Events.
filter(predicate: (PNEvent) -> Boolean)Allows for custom filtering of events delivered to the subscription based on the provided predicate. Useful for event-specific handling.

Sample code​

1

Method(s)​

Subscription and SubscriptionSet use the same methods to subscribe:

Subscribe​

To subscribe, you can use the following method:

1

Sample code​
1

Other examples​
Create a subscription set and add/remove subscriptions​
1

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:

1subscriptionSet.subscribe(SubscriptionCursor(timetoken = yourTimeToken))
* required
ParameterDescription
cursor *
Type: SubscriptionCursor
Cursor 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.
Sample code​
1

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.

No built-in event throttling

The PubNub SDK delivers every incoming event to your listener as it arrives — there is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.

To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.

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)​
1fun addListener(listener: EventListener)
Sample code​
1

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.

Sample code​
1

Remove event listener​

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

1subscription.setOnMessage(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)​

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

Sample code​

1

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.

Add DataSync listener​

DataSync publishes an event when an object (a user, channel, membership, or a custom entity or relationship) is created, updated, or deleted. To receive them, create a DataSync SDK entity for the object (DataSyncUser, DataSyncChannel, or DataSyncEntity), subscribe to it, and attach a dataSync listener.

A create event for a user, channel, or entity is delivered only on its own id. An update or delete event for a user, channel, or entity is also delivered on the id of every entity, user, or channel connected to it by a relationship or membership. A membership or relationship event, on create, update, or delete alike, is delivered on the channels of both linked entities and never on a channel named after the membership or relationship id. Refer to Where each event is delivered for the full mapping.

The dataSync listener works on all three scopes: the PubNub client, a Subscription, and a SubscriptionSet.

Events are off by default

To receive DataSync events, enable event publishing for the object's class in the Admin Portal. Refer to DataSync events for details.

Events are filtered per projection

An event is delivered once for each channel it fans out to, and each delivery carries only the fields that channel's projection exposes. The plain (__default__) channel carries only the fields declared under __default__, and a __{projection}__{id} channel carries only the fields declared under that projection. status is filtered the same way, through the class's declared projections for /status. id, eTag, createdAt, updatedAt, and expiresAt are always delivered unfiltered. delete events are never filtered. Refer to DataSync projections for details.

Method(s)​

To receive DataSync events, attach a dataSync listener through any of the following attachment points:

1// On the PubNub client, a Subscription, or a SubscriptionSet
2void addListener(EventListener listener)
3// @Override public void dataSync(PubNub pubnub, PNDataSyncEventResult result)
4
5// Single handler on the PubNub client, a Subscription, or a SubscriptionSet
6void setOnDataSync(OnDataSyncHandler onDataSyncHandler)

Using setOnDataSync(), you cannot have multiple listeners attached to the same scope. Assigning a new handler overwrites the previous one, and assigning null removes it.

The listener receives a PNDataSyncEventResult. Its getChannel() is the concrete data channel on which this copy of the event arrived. For a fanned-out event or a projection channel that is not the changed object's id, so identify the changed object through the message instead. The getExtractedMessage() method returns the parsed DataSync change. Its properties are:

PropertyDescription
source
Type: String
Always data-sync (hyphenated). This is the backend's wire-format value and differs intentionally from the dataSync naming used elsewhere in the SDK.
version
Type: String
The DataSync service payload version.
type
Type: String
The object kind as sent by the service: user, channel, membership, entity, or relationship. The kind follows the class's Global ancestor, so a custom subclass of User still reports user, while a custom entity class or relationship class reports the generic entity or relationship.
className
Type: String
The class name of the changed object, as a plain name. null when absent.
classLevel
Type: String
Where the class is defined: Global for the built-in User, Channel, and Membership classes, or SubKey for a class you defined on your own keyset. null when absent.
classVersion
Type: Integer
The class version of the changed object. null when absent.
event
Type: PNDataSyncSetEventType
The change type, CREATE or UPDATE. Only PNSetDataSync*EventMessage messages have it. A delete has its own message class instead.
data
Type: PNDataSync*Data
The object state of a create or update. Refer to the descriptions below.

Read each property through its getter, for example getClassName().

note
Class identity lives on the event, not in data

className, classLevel, and classVersion are reported once on the message and are not repeated inside data. There is no entity class or relationship class on data, unlike the objects returned by the DataSync API. Read classLevel alongside className when you need to tell a built-in class from one of your own that happens to share its name.

PNDataSyncEventMessage is a sealed class, so branch on its concrete type with instanceof checks and always handle the case where none matches. The shape of the message depends on the object kind and the event:

  • User, channel, and entity create and update events are PNSetDataSyncUserEventMessage, PNSetDataSyncChannelEventMessage, and PNSetDataSyncEntityEventMessage. Their data carries the current object state: id, status, payload, createdAt, updatedAt, eTag, and expiresAt.
  • Relationship create and update events are PNSetDataSyncRelationshipEventMessage. Their data carries the same fields plus entityAId and entityBId.
  • Membership create and update events are PNSetDataSyncMembershipEventMessage. Their data carries the same fields plus channelId and userId, the same names the DataSync API uses. A membership event never carries entityAId or entityBId.
  • Delete events are PNDeleteDataSyncUserEventMessage, PNDeleteDataSyncChannelEventMessage, PNDeleteDataSyncEntityEventMessage, PNDeleteDataSyncMembershipEventMessage, and PNDeleteDataSyncRelationshipEventMessage. Each carries only id and deletedAt, so a membership or relationship delete does not tell you the linked ids.
  • An event with a type or event value this SDK version does not know is a PNUnknownDataSyncEventMessage, which keeps the raw type, event, metadata, and data.

Apart from id, the status and payload of a create or update are null when the object has none, so guard the access when you read one.

DataSync events are server-generated, so the SDK never decrypts them, even when you configure a cryptoModule.

Sample code​

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

Other examples​

Use the setOnDataSync() handler​
1

Add the listener to the PubNub client​
1

Add the listener to a subscription set​
1

Delivery is at-least-once with no server-side de-duplication, so the same change, including a create, can arrive more than once. Handle events idempotently, keyed on the object id plus eTag or updatedAt.

To keep a full local copy of the object, fetch it once with pubnub.dataSync().getEntity() for the current state, then apply events as they arrive. Filter by type and data.id first because the channel also receives relationship and connected-entity fan-out. Compare the eTag or updatedAt on create and update events against your local copy to detect stale updates, and use id and deletedAt for delete events. To resolve the linked ids of a membership or relationship that is deleted, keep a local map from the membership or relationship id to its linked ids, filled from the create and update events.

When you filter on type, match the value for the kind you are tracking. A custom entity class reports entity and a custom relationship class reports relationship, while users, channels, and memberships report user, channel, and membership, so a filter hardcoded to entity silently drops every user and channel event.

For the fetch methods, refer to DataSync API. For the concurrency pattern, refer to the ETags concept documentation.

Unsubscribe​

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

Method(s)​

1

Sample code​

1

Returns​

None

Unsubscribe all​

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

Client scope

This method is only available on the PubNub object.

Method(s)​

1pubnub.unsubscribeAll()

Sample code​

1

Returns​

None

Publish (old)​

Not recommended

The use of this method is discouraged. Use Publish instead.

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

You should not JSON serialize the message and meta parameters when sending signals, messages, or files as the serialization is done automatically. Pass the full object as the message/meta payload and let PubNub take 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​
1["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details, check Calculating Message Payload Size Before Publish.

Need larger messages?

PubNub supports payloads larger than the standard limit, but raising it requires verifying compatibility with your use case.

Talk to our team to discuss increasing the message size limit for your use case.

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 Java SDK:

1this.pubnub.publish()
2 .message(Object)
3 .channel(String)
4 .shouldStore(Boolean)
5 .meta(Object)
6 .queryParam(HashMap)
7 .usePOST(Boolean)
8 .ttl(Integer);
* required
ParameterDescription
message *
Type: Object
Default:
n/a
The payload.
channel *
Type: String
Default:
n/a
Destination of the message (channel ID).
shouldStore
Type: Boolean
Default:
account default
Store in history.
If shouldStore is not specified, then the history configuration on the key is used.
meta
Type: Object
Default:
Not set
Meta data object which can be used with the filtering ability.
queryParam
Type: HashMap<string,string>
Default:
Not set
One 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 your PubNub Dashboard, and never returned in server responses.
usePOST
Type: Boolean
Default:
false
Use POST to publish.
ttl
Type: Integer
Default:
n/a
Set 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 unless you have message retention set to Unlimited on your keyset configuration in the Admin Portal.
  3. If shouldStore = false, the ttl parameter is ignored.
  4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
sync
Type: Command
Default:
n/a
Block the thread, exception thrown if something goes wrong.
async
Type: Consumer<Result>
Default:
n/a
Consumer of a Result of type PNPublishResult

Sample code​

Publish a message to a channel​
1

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:

MethodDescription
getTimetoken()
Type: Long
Returns a long representation of the timetoken when the message was published.

Other examples​

Publish with metadata​
1

Publishing JsonObject (Google GSON)​
1

Publishing JsonArray (Google GSON)​
1

Publishing JSONObject (org.json)​
1

Publishing JSONArray (org.json)​
1

Store the published message for 10 hours​
1

Fire (old)​

Not recommended

The use of this method is discouraged. Use Fire instead.

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 Java SDK:

1this.pubnub.fire()
2 .message(Object)
3 .channel(String)
4 .meta(Object)
5 .usePOST(Boolean);
* required
ParameterDescription
message *
Type: Object
Default:
n/a
The payload.
channel *
Type: String
Default:
n/a
Destination of the message (channel ID).
meta
Type: Object
Default:
Not set
Meta data object which can be used with the filtering ability.
usePOST
Type: Boolean
Default:
false
Use POST to publish.
sync
Type: Command
Default:
n/a
Block the thread, exception thrown if something goes wrong.
async
Type: Consumer<Result>
Default:
n/a
Consumer of a Result of type PNPublishResult

Sample code​

1

Response​

The fire() operation returns a PNPublishResult:

MethodDescription
getTimetoken()
Type: Long
Returns a long representation of the timetoken when the signal was published.

Signal (old)​

Not recommended

The use of this method is discouraged. Use Signal instead.

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 Java SDK:

1this.pubnub.signal()
2 .message(Object)
3 .channel(String);
* required
ParameterDescription
message *
Type: Object
The payload which will be serialized and sent.
channel *
Type: String
The channel ID which the signal will be sent to.
sync
Type: PNPublishResult
Executes the call. Blocks the thread, exception is thrown if something goes wrong.
async
Type: Consumer<Result>
Executes the call asynchronously.

Sample code​

1

Response​

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

MethodDescription
getTimetoken()
Type: Long
Returns a long representation of the timetoken when the signal was published.

Subscribe (old)​

Not recommended

The use of this method is discouraged. 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 for more details. Listeners should be added before calling the method.

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 ID. To subscribe to a channel ID 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 ID 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 Java SDK:

1pubnub.subscribe()
2 .channels(Array)
3 .channelGroups(Arrays)
4 .withTimetoken(Long)
5 .withPresence()
6 .execute();
* required
ParameterDescription
channels
Type: Array
Subscribe to channels, Either channel ID or channelGroup is required
channelGroups
Type: Array
Subscribe to channel groups, Either channel ID or channelGroup is required
withTimetoken
Type: Long
Pass a timetoken
withPresence()
Type: Command
Also subscribe to related presence information
execute() *
Type: Command
Command that will execute subscribe.

Sample code​

Subscribe to a channel:

1pubnub.subscribe()
2 .channels(Arrays.asList("my_channel")) // subscribe to channels
3 .execute();
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section.

Returns​

PNMessageResult

PNMessageResult is returned in the Listeners.

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

MethodDescription
getCategory()
Type: Enum of type PNStatusCategory.
See Status events for the Java SDK.
isError()
Type: Boolean
Is true in case of an error.

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

MethodDescription
getMessage()
Type: JsonElement
The message sent on the channel ID.
getSubscription()
Type: String
The channel group or wildcard subscription match (if exists).
getChannel()
Type: String
The channel ID for which the message belongs.
getTimetoken()
Type: Long
Timetoken for the message.
getUserMetadata()
Type: Object
User metadata.

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

MethodDescription
getEvent()
Type: String
Events like join, leave, timeout, state-change, interval.
getUuid()
Type: String
UUID for the event.
getTimestamp()
Type: Long
Timestamp for the event.
getOccupancy()
Type: Int
Current occupancy.
getState()
Type: JsonElement
State of the UUID.
getSubscription()
Type: String
The channel group or wildcard subscription match (if exists).
getChannel()
Type: String
The channel ID for which the message belongs.
getTimetoken()
Type: Long
Timetoken of the message.
getUserMetadata()
Type: Object
User metadata.

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

MethodDescription
getMessage()
Type: JsonElement
The signal sent on the channel ID.
getSubscription()
Type: String
The channel group or wildcard subscription match (if exists).
getChannel()
Type: String
The channel ID for which the signal belongs.
getTimetoken()
Type: Long
Timetoken for the signal.
getUserMetadata()
Type: Object
User metadata.

Other examples​

Basic subscribe with logging​
1

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.

1pubnub.subscribe()
2 .channels(Arrays.asList("my_channel1","my_channel2" ))
3 .execute();
Subscribing to a Presence channel​
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.

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#message(PubNub, PNMessageResult) callback.

1

Sample Responses​
Join event​
1

Leave event​
1

Timeout event​
1

State change event​
1

Interval event​
1

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:

1if (presence.getEvent().equals("interval")) {
2 presence.getTimestamp(); // <unix timestamp>
3 presence.getOccupancy(); // <# users in channel>
4 presence.getJoin(); // ["uuid1", "uuid2"]
5 presence.getTimeout(); // ["uuid3"]
6}

If the full interval message is greater than 30 KB (since the max publish payload is ∼32 KiB), 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.

1if (presence.getEvent().equals("interval")) {
2 presence.getTimestamp(); // <unix timestamp>
3 presence.getOccupancy(); // <# users in channel>
4 presence.getHereNowRefresh() // true
5}
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 (.).

1pubnub.subscribe()
2 .channels(Arrays.asList("foo.*"))
3 .execute();
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.*. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*.

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

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.

1

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.

1

Subscribe to the presence channel of a channel group​
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.

1

Unsubscribe (old)​

Not recommended

The use of this method is discouraged. Use Unsubscribe instead.

Description​

This function causes the client to remove an open TCP socket to the PubNub Real-Time Network and stop listening for messages on a specified channel ID.

Method(s)​

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

1pubnub.unsubscribe()
2 .channels(Array)
3 .channelGroups(Arrays)
4 .execute();
* required
ParameterDescription
channels
Type: Array
Unsubscribe from channels, Either channel ID or channelGroup is required
channelGroups
Type: Array
Unsubscribe from channel groups, Either channel ID or channelGroup is required
execute() *
Type: Command
Command that will execute unsubscribe.

Sample code​

Unsubscribe from a channel:

1

Unsubscribe from a channel group:

1

Unsubscribe from multiple channels:

1

Returns​

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

MethodDescription
getCategory()
Type: Enum of type PNStatusCategory.
See Status events for the Java SDK.
isError()
Type: Boolean
Is true in case of an error.

Was this page useful?

Last updated on