Publish/Subscribe API for PubNub Dart SDK

The foundation of the PubNub service is the ability to send a message and have it delivered anywhere 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

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 please check: https://support.pubnub.com/hc/en-us/articles/360051495932-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 Dart SDK:

pubnub.publish(
String channel,
dynamic message,
{Keyset? keyset,
String? using,
dynamic meta,
bool? storeMessage,
int? ttl}
)
ParameterTypeRequiredDefaultDescription
channelStringYesDestination of the message.
messageAnyYesThe payload.
keysetKeysetOptionalOverride for the PubNub default keyset configuration.
usingStringOptionalKeyset name from the keysetStore to be used for this method call.
metadynamicOptionalNot setMetadata object which can be used with the filtering ability.
storeMessageboolOptionalAccount defaultStore message in history.
If not specified, the decision depends on whether Message Persistence has been enabled for the key or not.
ttlintOptionalSet a per message time to live in Message Persistence.
1. If storeMessage = true, and ttl = 0, the message is stored with no expiry time.
2. If storeMessage = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
3. If storeMessage = 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:

var result = await pubnub.publish('myChannel', 'hello world!');

Returns

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

MethodTypeDescription
descriptionStringThe description, for example Sent.
timetokenintReturns an int representation of the timetoken when the message was published.

Other Examples

Publish with metadata

var result = await pubnub.publish('my_channel', 'hello', meta: '<json data>');

Publishing JsonObject (Google GSON)

var message = {'hello': 'world'};
var result = await pubnub.publish('my_channel', message);

Publishing JsonArray (Google GSON)

var message = ['hello', 'world'];
var result = await pubnub.publish('my_channel', message);

Publishing JSONObject (org.json)

var jsonString = '{"score": 40}';
var result = await pubnub.publish('my_channel', jsonDecode(jsonString));

Publishing JSONArray (org.json)

var jsonString = '''
[
{"score": 40},
{"score": 80}
]
''';
var result = await pubnub.publish('my_channel', jsonDecode(jsonString));

Store the published message for 10 hours

var result =
await pubnub.publish('my_channel', 'hello', storeMessage: true, ttl: 10);

Signal

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

pubnub.signal(
String channel,
dynamic message,
{Keyset? keyset,
String? using}
)
ParameterTypeRequiredDescription
channelStringYesDestination of the message.
messageAnyYesThe payload.
keysetKeysetOptionalOverride for the PubNub default keyset configuration.
usingStringOptionalKeyset name from the keysetStore to be used for this method call.

Basic Usage

Signal a message to a channel:

var result = await pubnub.signal('myChannel', 'signal!');

Response

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

MethodTypeDescription
descriptionStringThe description, for example Sent.
timetokenintReturns an int representation of the timetoken when the signal was published.

Subscribe

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 Subscription 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 retryPolicy to RetryPolicy.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 Dart SDK:

pubnub.subscribe(
{Set<String>? channels,
Set<String>? channelGroups,
bool withPresence = false,
Timetoken? timetoken,
Keyset? keyset,
String? using}
)
ParameterTypeRequiredDescription
channelsSet<String>Yeschannels to subscribe to. Either channel or channelGroup is required.
channelGroupsSet<String>YeschannelGroups to subscribe to. Either channel or channelGroup is required.
withPresenceboolOptionalAlso subscribe to related presence information.
timetokenTimetokenOptionalTimetoken to start the subscription from.
keysetKeysetOptionalOverride for the PubNub default keyset configuration.
usingStringOptionalKeyset name from the keysetStore to be used for this method call.

Basic Usage

Subscribe to a channel:

var channel = "my_channel";
var subscription = pubnub.subscribe(channels: {channel});

Returns

The subscribe() method returns a Subscription. For more information, refer to Subscription.

Subscription

A Subscription contains a Dart stream of messages from the channel(s) to which you are subscribed. You can transform that stream in the usual ways, or add a listener using listen.

Listeners

For a list of available listeners, refer to the Listeners section.

Cancel

The cancel() method cancels the subscription. This disposes of internal streams, so the subscription becomes unusable.

Method(s)
subscription.cancel();
Basic Usage
// var subscription = pubnub.subscribe(channels: {'my_channel'});
// active subscription available
await subscription.cancel();
Returns

The cancel() operation on Subscription doesn't return any object. It disposes of internal streams, so the subscription becomes unusable.

Dispose

The dispose() method is an alias for the cancel() method.

Pause

Pausing a subscription prevents the message and presence streams from emitting messages. Keep in mind that you may miss messages while subscription is paused. If subscription is currently paused, this method is a no-op.

Method(s)
subscription.pause() 
Basic Usage
var subscription = pubnub.subscribe(channels: {'my_channel'});
// active subscription available
subscription.pause();
Returns

The pause() operation on Subscription doesn't return any object. Pausing subscription prevents the messages and presence streams from emitting messages.

Resume

Resumes a paused subscription. If a subscription isn't paused, then this method is a no-op.

Method(s)
subscription.resume() 
Basic Usage
// If subscription is paused
subscription.resume();
Returns

The resume() operation on Subscription object doesn't return any object. If subscription isn't paused, then this method does nothing.

Other Examples

Basic subscribe with logging

// Create a root logger
var logger = StreamLogger.root('root', logLevel: Level.all);

// Subscribe to messages with a default printer
var sub = logger.stream.listen(
LogRecord.createPrinter(r'[$time] (${level.name}) $scope: $message'));

// Provide logging only for the parts that you are interested in.
var _ = await provideLogger(logger, () async {
var subscription = pubnub.subscribe(channels: {'test'});

var message = subscription.messages.first;

await pubnub.publish('test', {'message': 'My message'});

show all 19 lines

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.

var subscription = pubnub.subscribe(channels: {'my_channel', 'channel1'});

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

var subscription =
pubnub.subscribe(channels: {'my_channel'}, withPresence: true);

Sample Responses

Join Event

{
"Event": "join",
"Uuid": "175c2c67-uuid-uuid-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 2,
"State": null,
"Channel":" my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}

Leave Event

{
"Event": "leave",
"Uuid": "175c2c67-uuid-uuid-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 1,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}

Timeout Event

{
"Event": "timeout",
"Uuid": "175c2c67-uuid-uuid-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 0,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}

Custom Presence Event (State Change)

{
"Event": "state-change",
"Uuid": "175c2c67-uuid-uuid-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 1,
"State": {
"isTyping": true
},
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
show all 17 lines

Interval Event

{
"Event": "interval",
"Uuid": "175c2c67-uuid-uuid-8f4b-1db94f90e39e",
"Timestamp": 1345546797,
"Occupancy": 2,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"HereNowRefresh": false
}

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
  • timed out

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

{
"Event": "interval",
"Uuid": "175c2c67-uuid-uuid-8f4b-1db94f90e39e",
"Timestamp": <unix timestamp>,
"Occupancy": <# users in channel>,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": ["uuid2", "uuid3"],
"Timeout": ["uuid1"],
"Leave": null,
"HereNowRefresh": false
}

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.

{
"Event": "interval",
"Uuid": "175c2c67-uuid-uuid-8f4b-1db94f90e39e",
"Timestamp": <unix timestamp>,
"Occupancy": <# users in channel>,
"State": null,
"Channel": "my_channel",
"Subscription": "",
"Timetoken": 15034141109823424,
"UserMetadata": null,
"Join": null,
"Timeout": null,
"Leave": null,
"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 (.).

var subscription = pubnub.subscribe(channels: {'foo.*'});
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.*.

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.

var subscription = pubnub.subscribe(channelGroups: {'cg1'});

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

var subscription =
pubnub.subscribe(channelGroups: {'cg1', 'cg2'}, withPresence: true);
Last updated on