Subscribe API: not recommended methods for JavaScript SDK
This page documents the superseded pubnub.subscribe({ channels }), pubnub.unsubscribe({ channels }), and pubnub.unsubscribeAll() methods of the PubNub JavaScript SDK. Subscribe is a current API, and these methods are an older way to call it. These methods remain for apps that already use them. New apps create subscriptions and subscription sets instead. To move an existing app, see the JavaScript v11 migration guide.
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.
To add a listener, see 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 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.
Connectivity notification
You can be notified of connectivity via the listener, on establishing connection the statusEvent.category returns PNConnectedCategory.
Wait for the connect event before you publish. This avoids a race condition on clients that subscribe and immediately publish messages before subscribe has completed.
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 channels. Unsubscribing from all channels resets the last-received timetoken, so the subscription can have gaps that lead to message loss.
Method(s)
To Subscribe to a channel, you can use the following method(s) in the JavaScript SDK:
1pubnub.subscribe({
2 channels: Array<string>,
3 channelGroups: Array<string>,
4 withPresence: boolean,
5 timetoken: number
6}): Promise<SubscribeResponse>;
channelsrequired#- Specifies the
channelsto subscribe to. You can specify multiplechannelsas a list or as an array. channelGroups#- Specifies the
channelGroupsto subscribe to. Specifying eitherchannelsorchannelGroupsis mandatory. withPresence#- If
trueit also subscribes to presence instances. timetoken#- Specifies
timetokenfrom which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.
Sample code
Subscribe to a channel:
1
Event listeners
The response of the call is handled by adding a Listener. See Event Listeners. Listeners should be added before calling the method.
Returns
The following objects will be returned in the status response
| Object | Description |
|---|---|
category | PNConnectedCategory |
operation | PNSubscribeOperation |
affectedChannels | The channels affected in the operation, of type array. |
subscribedChannels | All the current subscribed channels, of type array. |
affectedChannelGroups | The channel groups affected in the operation, of type array. |
lastTimetoken | The last timetoken used in the subscribe request, of type long. |
currentTimetoken | The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long. |
subscribedChannels and lastTimetoken are present only when you set enableEventEngine to false in the configuration, which keeps the legacy subscription manager. With the default value of true, the status has neither of them. The example shows the status with enableEventEngine: false.
1{
2 category: 'PNConnectedCategory',
3 operation: 'PNSubscribeOperation',
4 affectedChannels: ['my_channel_1'],
5 subscribedChannels: ['my_channel_1'],
6 affectedChannelGroups: [],
7 lastTimetoken: '14974492380756600',
8 currentTimetoken: '14974492384874375'
9}
The following objects will be returned in the subscribe message response
| Object | Description |
|---|---|
channel | The channel ID for which the message belongs. |
subscription | The channel group or wildcard subscription match (if exists). |
timetoken | Publish timetoken. |
message | The payload. |
actualChannel | Deprecated. Use property channel. |
subscribedChannel | Deprecated. Use property subscription. |
1{
2 actualChannel: null,
3 channel: "my_channel_1",
4 message: "Hello World!",
5 publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
6 subscribedChannel: "my_channel_1",
7 subscription: null,
8 timetoken: "14966804541029440"
9}
The following objects will be returned in the Presence response
| Object | Description |
|---|---|
action | Can be join, leave, state-change or timeout. |
channel | The channel ID for which the message belongs. |
occupancy | No. of users connected with the channel ID. |
state | User State. |
subscription | The channel group or wildcard subscription match (if exists) |
timestamp | Current timetoken. |
timetoken | Publish timetoken. |
uuid | UUIDs of users who are connected with the channel ID. |
1{
2 category: 'PNConnectedCategory',
3 operation: 'PNSubscribeOperation',
4 affectedChannels: ['my_channel_1'],
5 subscribedChannels: ['my_channel_1'],
6 affectedChannelGroups: [],
7 lastTimetoken: '14974492380756600',
8 currentTimetoken: '14974492384874375'
9}
Other examples
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.
1
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.
1
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. See Enable the features your app calls.
For wildcard subscribe, check Enable Wildcard Subscribe in the add-on settings.
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 (.).
1
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
Subscribing with state requires the Presence add-on, as described in Subscribing to a Presence channel.
Required user ID
Always set the userId to uniquely identify the user or device that connects to PubNub. Keep the same userId for the lifetime of the user or the device. If you don't set the userId, you can't 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. See Enable the features your app calls.
1
Subscribe to the presence channel of a channel group
Requires Stream Controller and Presence add-ons
This method requires that both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. See Enable the features your app calls.
1
Subscribing to multiple channel groups
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
1
Subscribing to a channel and channel group simultaneously
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
1
Sample Responses
Join event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "join",
7 "timetoken": "15119466699655811",
8 "occupancy": 2,
9 "uuid": "User1",
10 "timestamp": 1511946669
11}
Leave event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "leave",
7 "timetoken": "15119446002445794",
8 "occupancy": 1,
9 "uuid": "User1",
10 "timestamp": 1511944600
11}
Timeout event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "timeout",
7 "timetoken": "15119519897494311",
8 "occupancy": 3,
9 "uuid": "User2",
10 "timestamp": 1511951989
11}
State change event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "state-change",
7 "state": {
8 "isTyping": true
9 },
10 "timetoken": "15119477895378127",
11 "occupancy": 5,
12 "uuid": "User4",
13 "timestamp": 1511947789
14}
Interval event
1{
2 "action": "interval",
3 "occupancy": 2,
4 "timestamp": 1511947739
5}
When a channel is in interval mode with the presence_deltas pnconfig flag enabled, the interval message can also include the following fields. Each field holds an array of the UUIDs that changed since the last interval message.
- 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:
1{
2 "action":"interval",
3 "timestamp":1548340678,
4 "occupancy":2,
5 "join":["pn-94bea6d1-2a9e-48d8-9758-f1b7162631ed","pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"]},
6 "timedout":["pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"],
7 "b":"my-channel-pnpres"
8}
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.
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "interval",
7 "timetoken": "15119477396210903",
8 "occupancy": 4,
9 "timestamp": 1511947739,
10 "here_now_refresh" : true
11}
You can be notified of connectivity status, message, and presence notifications via the listeners.
Listeners should be added before calling the method.
Add listeners
1
Remove listeners
1
Listener status events
| Category | Description |
|---|---|
PNNetworkUpCategory | The SDK detected that the network is online. |
PNNetworkDownCategory | The SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK isn't able to reach PubNub servers. Possible causes are a device that isn't connected to the internet, a lost internet connection, trouble at your internet service provider, or a proxy that blocks the SDK. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNConnectedCategory | SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. |
PNAccessDeniedCategory | Access Manager permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with a bad response error because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish a connection to PubNub due to a timeout. |
PNRequestMessageCountExceedCategory | The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
PNUnknownCategory | Returned when the subscriber gets a non-200 HTTP response code from the server. |
Unsubscribe (old)
Not recommended
The use of this method is discouraged. 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 channels. Unsubscribing from all channels resets the last-received timetoken, so the subscription can have gaps that lead to message loss.
Method(s)
To Unsubscribe from a channel, you can use the following method(s) in the JavaScript SDK:
1pubnub.unsubscribe({
2 channels: Array<string>,
3 channelGroups: Array<string>
4}): Promise<UnsubscribeResponse>;
Sample code
Unsubscribe from a channel:
1
Returns
The output below demonstrates the response to a successful call:
1{
2 "action" : "leave"
3}
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. See Enable the features your app calls.
1
Example response
1{
2 "action" : "leave"
3}
Unsubscribing from multiple channel groups
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
1
Unsubscribe all (old)
Not recommended
The use of this method is discouraged. Use Unsubscribe all instead.
Unsubscribe from all channels and all channel groups
Method(s)
1unsubscribeAll()
Sample code
1
Returns
None