Publish/Subscribe API for PubNub Java SDK
Breaking changes since 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 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.
Publish
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.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Best practices
- You must initialize PubNub with the
publishKey
. - You must create a Channel entitywhere you will publish to.
Entity
A subscribable object within a PubNub SDK that allows you to perform context-specific operations. - You don't have to be subscribed to a channel to publish to it.
- You cannot publish to multiple channels simultaneously.
You can secure the messages with SSL/TLS by setting ssl
to true
during initialization. You can also encrypt messages.
The message can contain any JSON-serializable data (Objects, Arrays, Ints, Strings) and shouldn't contain any special classes or functions. String content can include any single-byte or multi-byte UTF-8 characters.
Don't JSON serialize
You should not JSON serialize the message
and meta
parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB, including the final escaped character count and the channel name. An optimal message size is under 1800 bytes.
If the message you publish exceeds the configured size, you receive a Message Too Large
error. If you want to learn more or calculate your payload size, refer to Message Size Limit.
You can publish as fast as bandwidth conditions 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, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
- 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 according to your app's latency needs, for example no more than 5 messages per second.
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.
Channel channel = pubnub.channel("myChannel");
channel.publish(Object message)
.shouldStore(Boolean)
.meta(Object)
.queryParam(HashMap)
.usePOST(Boolean)
.ttl(Integer);
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object | Yes | The payload. | |
shouldStore | Boolean | Optional | account default | Store in history. If shouldStore is not specified, then the history configuration on the key is used. |
meta | Object | Optional | Not set | Meta data object which can be used with the filtering ability. |
queryParam | HashMap<string,string> | Optional | 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 | Boolean | Optional | false | Use POST to publish . |
ttl | Integer | Optional | Set a per message time to live in Message Persistence.
| |
sync | Command | Optional | Block the thread, exception thrown if something goes wrong. | |
async | Consumer<Result> | Optional | Consumer of a Result of type PNPublishResult |
Basic Usage
Publish a message to a channel
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubNub.channel("myChannel");
JsonObject position = new JsonObject();
position.addProperty("lat", 32L);
position.addProperty("lng", 32L);
System.out.println("before pub: " + position);
channel.publish(position)
.async(result -> {
result.onSuccess(res -> {
show all 19 linesSubscribe 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
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel");
channel.publish(Arrays.asList("hello", "there"))
.shouldStore(true)
.meta(<Object>) // optional meta data object which can be used with the filtering ability.
.usePOST(true)
.async(result -> { /* check result */ });
Publishing JsonObject (Google GSON)
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel");
JsonObject position = new JsonObject();
position.addProperty("lat", 32L);
position.addProperty("lng", 32L);
System.out.println("before pub: " + position);
channel.publish(position)
.async(result -> {
show all 19 linesPublishing JsonArray (Google GSON)
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel");
JsonArray position = new JsonArray();
position.add(32L);
System.out.println("before pub: " + position);
channel.publish(position)
.async(result -> {
result.onSuccess(res -> {
show all 18 linesPublishing JSONObject (org.json)
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel");
JSONObject position = new JSONObject();
position.put("lat", 32L);
position.put("lng", 32L);
System.out.println("before pub: " + position);
channel.publish(position.toMap())
.async(result -> {
result.onSuccess(res -> {
show all 18 linesPublishing JSONArray (org.json)
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel");
JSONArray position = new JSONArray();
position.put(32L);
System.out.println("before pub: " + position);
channel.publish(position.toList())
.async(result -> {
result.onSuccess(res -> {
System.out.println("pub timetoken: " + res.getTimetoken());
show all 17 linesStore the published message for 10 hours
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel");
PNPublishResult result = channel.publish("test-message")
.shouldStore(true)
.ttl(10)
.sync();
Response
The publish()
operation returns a PNPublishResult
:
Method | Type | Description |
---|---|---|
getTimetoken() | Long | Returns a long representation of the timetoken when the signal was published. |
Fire
The fire endpoint allows the client to send a message to Functions Event Handlers. 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.
- Prerequisites and limitations
- 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)
Channel channel = pubnub.channel("myChannel");
channel.fire(Object message)
.meta(Object)
.usePOST(Boolean);
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object | Yes | The payload. | |
meta | Object | Optional | Not set | Meta data object which can be used with the filtering ability. |
usePOST | Boolean | Optional | false | Use POST to publish . |
sync | Command | Optional | Block the thread, exception thrown if something goes wrong. | |
async | Consumer<Result> | Optional | Consumer of a Result of type PNPublishResult |
Basic Usage
Fire a message to a channel
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel")
channel.fire(Arrays.asList("hello", "there"))
.usePOST(true)
.async(result -> {
result.onSuccess(res -> {
System.out.println("publish worked! timetoken: " + res.getTimetoken());
}).onFailure(exception -> {
System.out.println("error happened while publishing: " + exception.toString());
});
});
Response
The fire()
operation returns a PNPublishResult
:
Method | Type | Description |
---|---|---|
getTimetoken() | Long | Returns a long representation of the timetoken when the signal was published. |
Signal
The signal()
function is used to send a signalSignal
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.
- Prerequisites and limitations
- Signal vs. Message
- 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.
- The message size is limited to 64 bytes or less.
- Signals cost less compared to messages.
- A signal's data isn't saved in Message Persistence.
- There are no SLAs, even though signals generally provide the same reliability and latency as published messages.
- Signals can't invoke Mobile Push Notifications.
Method(s)
Channel channel = pubnub.channel("myChannel");
channel.signal(Object message);
Parameter | Type | Required | Description |
---|---|---|---|
message | Object | Yes | The payload which will be serialized and sent. |
sync | PNPublishResult | Optional | Executes the call. Blocks the thread, exception is thrown if something goes wrong. |
async | Consumer<Result> | Optional | Executes the call asynchronously. |
Basic Usage
Signal a message to a channel
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "demo");
configBuilder.publishKey("demo");
PNConfiguration pnConfiguration = configBuilder.build();
Channel channel = pubnub.channel("myChannel")
channel.signal("Hello everyone!")
.async(result -> {
result.onSuccess(res -> {
Long timetoken = res.getTimetoken(); // signal message timetoken
}).onFailure(exception -> {
exception.printStackTrace();
});
});
Response
The signal()
operation returns a PNPublishResult
:
Method | Type | Description |
---|---|---|
getTimetoken() | Long | Returns 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 singlepubnub
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 Subscription
s is useful for handling various message/event types differently in each channel.
// Entity-based, local-scoped
// Specify the channel for subscription
Channel myChannel = pubnub.channel("channelName")
// Create subscription options, if any
SubscriptionOptions options = SubscriptionOptions.receivePresenceEvents()
// Return a Subscription object that is used to establish the subscription
Subscription subscription = myChannel.subscription(options)
// Activate the subscription to start receiving events
subscription.subscribe()
Parameter | Type | Required | Description |
---|---|---|---|
options | SubscriptionOptions | No | Subscription 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(
Set<String> channels,
Set<String> channelGroups,
SubscriptionOptions options
)
Parameter | Type | Required | Description |
---|---|---|---|
→ channels | Set<String> | No | Set of channel names to subscribe to. Use an empty set for no channels. |
→ channelGroups | Set<String> | No | Set of channel group names to subscribe to. Use an empty set for no channel groups. |
→ options | SubscriptionOptions | No | 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:
Option | Description |
---|---|
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
SubscriptionSet subscriptionSet = pubnub.subscriptionSetOf(
Set.of("my_channel", "other_channel"),
Collections.emptySet(),
EmptyOptions.INSTANCE);
// Step 2: Subscribe using the subscription set
subscriptionSet.subscribe()
Other examples
Create a subscription set from 2 individual subscriptions
// Create subscriptions
Subscription subscription1 = pubnub.channel("channelName").subscription();
Subscription subscription2 = pubnub.channelGroup("channelGroup").subscription();
// Combine into a subscription set
SubscriptionSet subscriptionSet = subscription1.plus(subscription2);
// Add another subscription to the set
subscriptionSet.add(subscription3);
// Remove a subscription from the set
subscriptionSet.remove(subscription3);
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))
Parameter | Type | Required | Description |
---|---|---|---|
cursor | SubscriptionCursor | Yes | 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. |
Basic usage
// Define the channels to subscribe to
Set<Channel> channels = setOf("my_channel", "other_channel")
// Create a subscription set with specified channels and subscription options
SubscriptionSet subscriptionSet = pubnub.subscriptionSetOf(channels, options)
// Define the timetoken for where the subscription should start
Long 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
Subscription 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 56 linesHandle 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 linesRemove 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.
When you initialized your PubNub client with enableEventEngine
set to true
(default option), the SDK will emit various statuses depending on your client network connection.
If you use the deprecated methods for subscribing and had enableEventEngine
set to false
, the status list the SDK emits is different.
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 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
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
For further details, check Calculating Message Payload Size Before Publish.
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:
this.pubnub.publish()
.message(Object)
.channel(String)
.shouldStore(Boolean)
.meta(Object)
.queryParam(HashMap)
.usePOST(Boolean)
.ttl(Integer);
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object | Yes | The payload. | |
channel | String | Yes | Destination of the message . | |
shouldStore | Boolean | Optional | account default | Store in history. If shouldStore is not specified, then the history configuration on the key is used. |
meta | Object | Optional | Not set | Meta data object which can be used with the filtering ability. |
queryParam | HashMap<string,string> | Optional | 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 | Boolean | Optional | false | Use POST to publish . |
ttl | Integer | Optional | Set a per message time to live in Message Persistence.
| |
sync | Command | Optional | Block the thread, exception thrown if something goes wrong. | |
async | Consumer<Result> | Optional | Consumer of a Result of type PNPublishResult |
Basic Usage
Publish a message to a channel
JsonObject position = new JsonObject();
position.addProperty("lat", 32L);
position.addProperty("lng", 32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position)
.channel("my_channel")
.async(result -> {
result.onSuccess(res -> {
System.out.println("pub timetoken: " + res.getTimetoken());
});
});
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:
Method | Type | Description |
---|---|---|
getTimetoken() | Long | Returns a long representation of the timetoken when the message was published. |
Other Examples
Publish with metadata
pubnub.publish()
.message(Arrays.asList("hello", "there"))
.channel("suchChannel")
.shouldStore(true)
.meta(<Object>) // optional meta data object which can be used with the filtering ability.
.usePOST(true)
.async(result -> { /* check result */ });
Publishing JsonObject (Google GSON)
JsonObject position = new JsonObject();
position.addProperty("lat", 32L);
position.addProperty("lng", 32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position)
.channel("my_channel")
.async(result -> {
result.onSuccess(res -> {
System.out.println("pub timetoken: " + res.getTimetoken());
});
});
Publishing JsonArray (Google GSON)
JsonArray position = new JsonArray();
position.add(32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position)
.channel("my_channel")
.async(result -> {
result.onSuccess(res -> {
System.out.println("pub timetoken: " + res.getTimetoken());
});
});
Publishing JSONObject (org.json)
JSONObject position = new JSONObject();
position.put("lat", 32L);
position.put("lng", 32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position.toMap())
.channel("my_channel")
.async(result -> {
result.onSuccess(res -> {
System.out.println("pub timetoken: " + res.getTimetoken());
});
});
Publishing JSONArray (org.json)
JSONArray position = new JSONArray();
position.put(32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position.toList())
.channel("my_channel")
.async(result -> {
result.onSuccess(res -> {
System.out.println("pub timetoken: " + res.getTimetoken());
});
});
Store the published message for 10 hours
PNPublishResult result = pubnub.publish()
.channel("coolChannel")
.message("test")
.shouldStore(true)
.ttl(10)
.sync();
Fire (deprecated)
The fire endpoint allows the client to send a message to Functions Event Handlers. 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:
this.pubnub.fire()
.message(Object)
.channel(String)
.meta(Object)
.usePOST(Boolean);
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object | Yes | The payload. | |
channel | String | Yes | Destination of the message . | |
meta | Object | Optional | Not set | Meta data object which can be used with the filtering ability. |
usePOST | Boolean | Optional | false | Use POST to publish . |
sync | Command | Optional | Block the thread, exception thrown if something goes wrong. | |
async | Consumer<Result> | Optional | Consumer of a Result of type PNPublishResult |