Subscriptions
As PubNub allows you to have hundreds or even thousands of subscriptions, it's vital to understand how to manage them efficiently.
Read on to understand what subscriptions and subscription sets are, and how to manage multiple channels with channel groups, wildcards, and Message Filters.
Receiving messages
To receive and handle incoming messages, signals, and events, you have to add an event listener first. If you're new to PubNub, make sure to check out how to set up your account as well.
Subscription types
The basic types of subscriptions are entityEntity
A subscribable object within a PubNub SDK that allows you to perform context-specific operations.Subscription
and SubscriptionSet
(although naming may vary between SDKs). For more information, refer to Entities.
Entity-enabled SDKs
Not all PubNub SDKs currently support entities. Refer to each SDK's API documentation for more information.
Subscription type | When to use | Sample usage |
---|---|---|
Subscription | When you want to introduce more granularity and flexibility to the way you handle particular events. | If you want to handle the same message differently on two (or however many) channels, you can create a separate subscription for each channel and attach different event listeners. |
SubscriptionSet | When you want to introduce common functionality to a number of events. | If you want to have a common logic for specific updates (for example, handling status updates), you can create a subscription set with all channels where user's presence is to be monitored and attach a single event listener. |
Both Subscription
and SubscriptionSet
objects have intuitive interfaces for subscription-related operations (like switching between the active and inactive states) and working with listeners. On top of that, you can create subscription sets from existing entity-scoped subscriptions if you decide you need to handle a bunch of subscriptions similarly.
Subscription options
You can parametrize the real-time data stream created using the Subscription
and SubscriptionSet
objects by specifying optional subscription options. Those options are shared across SDKs although you have to consider programming language differences in naming conventions.
Available options include:
Subscription option | Description |
---|---|
filter | Allows you to specify arbitrary filtering for events coming through the subscription. |
receivePresenceEvents | Allows you to decide whether to receive presence updates. |
For more information on how to use the subscription options in each SDK, refer to each SDK's Subscribe section of the API documentation, for example, in JavaScript.
Create subscriptions
Each SDK has dedicated methods to create subscriptions and subscription sets. For more information on managing subscriptions, refer to each SDK's Subscribe section of the API documentation, for example, JavaScript.
Subscribe to Channels
Once the listener object is established, the client can request to subscribe to individual channels. Subscribing to channels initiates a connection with the PubNub Platform which triggers a connection status event. This connection is kept open for the duration that the client stays subscribed to at least one channel. Any user subscribing to a channel receives messages in under 100ms, regardless of location.
Default subscribe timeout
There is a default timeout of 310 seconds (~5 min) for all requests related to subscribed channels that the client sends to the server. You can reduce this limit in your client configuration by specifying a different value for the subscribeTimeout
parameter.
The client can subscribe to several channels simultaneously through a single open connection. Typically, you subscribe to channels on app load. As the user navigates through your app, your app can remain subscribed to all the channels so it continues to receive messages on all of them. Alternatively, you can implement your app in a way that it subscribes and unsubscribes from channels as the user navigates through the app.
Configuration
If you want a single client to subscribe to multiple channels, you must have the Stream Controller feature enabled on your app's keyset in the Admin Portal to use the following subscription options:
- Channel Multiplexing — subscribing to multiple channels in a single API call
- Wildcard Subscriptions — subscribing to groups of channels that share a common naming pattern, like
news.*
- Channel Groups — creating named groups of channels and then subscribing to the group as a whole
Contrary to other features that you must specifically enable, Stream Controller is active by default on all new keysets.
Option | Description |
---|---|
Enable Wildcard Subscribe | An option that lets you subscribe to groups of channels with a shared naming pattern, like *.chat.* |
Channel group limit | The maximum number of channels you can add to channel groups. The default limit of 1,000 channels applies to all new keysets and can be modified if you have a paid account — you can then either lower the limit or increase it up to 2,000 channels. |
Signal Channel Subscribe
To receive Signals, you don't need a different subscription to the channel, but you do need a separate signal
event listener as mentioned in the Adding a Listener section.
Channel Multiplexing
Subscribing to multiple channels from a single client is called multiplexing. You can subscribe to one or more channels by creating many individual subscription objects or subscription sets. You can also create individual subscriptions and create a subscription set from them when their number increases.
Multiplexing allows each client to subscribe to a combination of channels of their choosing and change that selection at any time.
Multiplexing is designed for a relatively small number of channels. While there is no hard limit, PubNub strongly recommends multiplexing no more than 30 channels for any subscribe, and possibly fewer if you are deploying a larger application. For bigger channel subscribe groupings, you should consider using Channel Groups.
You can subscribe to one or more channels in a single request or you can spread those requests out in your application's flow. For example, a client might subscribe to chats.room1
now and then later subscribe to chats.room2
. Doing so will simply add chats.room2
to the current list of channels that have already been subscribed as if you subscribed to them at the same time.
For example, below is how you would subscribe to a channel chats.room1
when the user of your app enter their first chat room.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
const channel = pubnub.channel('chats.room1');
channel.subscription().subscribe();
let subscription1 = pubnub.channel("chants_room1").subscription()
[self.pubnub subscribeToChannels: @[@"chats.room1"] withPresence:NO];
pubnub.subscribe().channels(Arrays.asList("chats.room1")).execute();
Subscription subscription1 = pubnub.Channel("chats_room1").Subscription()
subscription1.Subscribe<object>()
channel = pubnub.channel("chats.room1")
t1_subscription = channel.subscription()
t1_subscription.subscribe()
The user continues to use your application, and then decides to enter another chat room, chats.room2
.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
// create a subscription from a channel entity
const channel = pubnub.channel('chats.room1')
const subscription1 = channel.subscription({ receivePresenceEvents: true });
// create a subscription from a channel entity
const channelGroup = pubnub.channel('chats.room2')
const subscription2 = channel.subscription();
const subscriptionSet = subscription1.addSubscription(subscription2);
subscriptionSet.subscribe();
// Create a subscription from a channel entity
let subscription1 = pubnub.channel("chats.room1").subscription()
// Create a subscription from a channel group entity
let subscription2 = pubnub.channelGroup("chats.room2").subscription()
// Create a subscription set from individual entities
let subscriptionSet = SubscriptionSet(subscriptions: [subscription1, subscription2])
[self.pubnub subscribeToChannels: @[@"chats.room2"] withPresence:NO];
pubnub.subscribe().channels(Arrays.asList("chats.room2")).execute();
Subscription subscription1 = pubnub.Channel("chats_room2").Subscription()
subscription1.Subscribe<object>()
channel2 = pubnub.channel("chats.room2")
t2_subscription = channel.subscription()
t2_subscription.subscribe()
The result is that the user is now subscribed to both chat room channels.
You can also leverage Channel Groups and Wildcard Subscribe. Below you'll be briefly introduced to these two alternative subscription management features.
Enable Stream Controller
Multiplexing is available by default, regardless of your Admin Portal configuration. However, to use the Wildcard Subscribe and Channel Groups features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.
Channel Groups
You can think of a channel group like a pointer to a list of channels on your server. If your application requires listening to large numbers of channels at once, channel groups allow you to send a single call which may subscribe to up to 100 channels. By default, each individual client can subscribe to a maximum of 10 channel groups for a total of up to 1,000 channels.
Modify limits for channels in channel groups
The default limit of 1,000 channels in channel groups per keyset applies to all new keysets created in the Admin Portal. If you're on a paid account, you can modify that limit for your app in the Admin Portal by changing the value for the Channel group limit on your keyset configuration under the Stream Controller section. You can either lower the default limit or increase it up to 2,000 channels.
Subscribe vs. Publish to Channel Groups
Channel groups can also be thought of as a subscribe group, because you can only subscribe to a channel group and you can't publish to a channel group. There are definite advantages to using channel groups when your clients must subscribe to a lot of channels. Your server adds channels to a channel group and clients can subscribe to all those channels contained in the channel group simply by subscribing to that channel group.
Your clients may not need to listen to that many channels, but channel groups make it possible for your server to manage the channels that the client is subscribed to by adding and removing channels on behalf of the clients.
To use a channel group, instead of multiplexing, there is just one additional step: add channels to a channel group.
Add channels to a channel group. This also creates the channel group if it doesn't already exist. This should be performed by your server for security and ease of management.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
pubnub.channelGroups.addChannels({
channels: ["chats.room1", "chats.room2", "alerts.system"]
channelGroup: "cg_user123"
},
function(status) {
console.log(status);
}
);
pubnub.add(
channels: ["chats.room1", "chats.room2", "alerts.system"],
to: "cg_user123"
) { result in
switch result {
case let .success(response):
print("succeeded: \(response)")
case let .failure(error):
print("failed: \(error.localizedDescription)")
}
}
[self.pubnub addChannels: @[@"chats.room1", @"chats.room2", @"alerts.system"]
toGroup:"cg_user123" withCompletion:^(PNAcknowledgmentStatus *status) {
// handle success/error
}];
pubnub.addChannelsToChannelGroup()
.channelGroup("cg_user123")
.channels(Arrays.asList("chats.room1", "chats.room2", "alerts.system"))
.async(result -> { /* check result */ });
pubnub.AddChannelsToChannelGroup()
.ChannelGroup("cg_user123")
.Channels(new string[] {"chats.room1", "chats.room2", "alerts.system"})
.Execute(new PNChannelGroupsAddChannelResultExt((result, status) => {
// handle success/error
}
));
pubnub.add_channel_to_channel_group()\
.channels(["chats.room1", "chats.room2", "alerts.system"])\
.channel_group("cg_user123")\
.sync()
The client subscribes to the channel group.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
const channelGroup = pubnub.channelGroup('cg_user123');
channelGroup.subscribe();
let subscription = pubnub.channelGroup("cg_user123").subscription()
subscription.subscribe()
[self.pubnub subscribeToChannelGroups:@["cg_user123"] withPresence:true];
pubnub.subscribe()
.channelGroups(Arrays.asList("cg_user123"))
.withPresence()
.execute();
Subscription subscription1 = pubnub.ChannelGroups("cg_user123").Subscription(SubscriptionOptions.ReceivePresenceEvents)
subscription1.Subscribe<object>()
channel_group = pubnub.channel_group("cg_user123")
t3_subscription = channel_group.subscription()
t3_subscription.subscribe()
When messages are published to any of the channels in this channel group, it will be received in the message handler of the client's listener. The channel group subscribes can also be enabled with withPresence
parameter to start receiving presence events for all the channels in the Channel Group.
Subscription with Presence
You must create a subscription with Presence enabled to receive Presence events. For more information, refer to each SDK's Publish and Subscribe documentation.
Be aware of whether this is necessary for your use case or not. You can separate channels into two channels groups: cg_presence_user123
(channels with presence tracking) and cg_user123
(channels without presence tracking). This can all be done on the client app. but when we talk about channel access security (Access Manager), it will be clear why clients should never be able to add/remove channels to/from a channel group.
Additionally, with Channel Groups your server can force a client to unsubscribe from a particular channel just by removing that channel from the channel group that the client is subscribed to.
Channel Group Names
Channel groups can be shared just like channels. For example, you may want to create a channel group called cg_sports
. Multiple clients can subscribe to this shared channel group and your server can add new channels related to sports and all the clients will automatically be subscribed to those new channels.
And there is no requirement to prefix the name with cg_
. It's only a convention that makes it easy to recognize Channel Groups. Feel free to use a naming convention that works best for your requirements and design style.
Channel Group Names
Channel Group names have the same rules as Channel names with one exception: you can't use a period in the name. This means that wildcard features do not apply to Channel Groups.
Just because you're using Channel Groups does not mean you can't also subscribe to individual channels. Sometimes it may be convenient to subscribe to a particular channel directly while also subscribing to a separate Channel Group. You can specify channels and channel groups in the same subscribe call or make individual subscribe calls. And channel groups can be multiplexed, too.
Wildcard Subscribe
Wildcard Subscribe channelName.*
can be used to subscribe to a hierarchical list of channels. It's similar to Channel Group in that you can subscribe to lots of channels with a single name declaration. For example, you specify a wildcard channel pattern like sports.*
, and your app will subscribe to all channel names that match that pattern: sports.cricket
, sports.lacrosse
. This list can be virtually infinite in number with some limitations described in the next section.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
const channel = pubnub.channel("alerts.*");
channel.subscription().subscribe();
let subscription1 = pubnub.channel("alerts.*").subscription()
[self.pubnub subscribeToChannels: @[@"alerts.*", @"chats.team1.*"] withPresence:YES];
pubnub.subscribe()
.channels(Arrays.asList("alerts.*", "chats.team1.*")
.withPresence())
.execute();
SubscriptionSet subscriptionSet = pubnub.Subscription(
new string[] {"alerts.*", "chats.team1.*"},
SubscriptionOptions.ReceivePresenceEvents
)
subscription_set1 = pubnub.subscription_set(channels=["alerts.*", "chats.team1.*"])
subscription_set1.subscribe(with_presence = True)
Wildcard Subscribe Rules
There are some limits to what you can do with the Wildcard Subscribe. Below is a quick summary of the rules:
- You're limited to two dots (three levels). For example, you can subscribe to
a.*
ora.b.*
but nota.b.c.*
. - A wildcard pattern must always end with
.*
. In other words, the*
can't be in the middle of the pattern (a.*.c
, isn't valid). - Just like Channel Groups, you can not publish to a wildcard channel pattern.
Message Filters
With the metadata information being sent with the published message, we can now leverage Message Filters to omit messages that aren't important for a particular client. For example, filter out messages that the client published using its User ID.
In the following code examples, the userId
variable is used as a placeholder variable that would hold the User ID value for the client. For your servers, this value would be pulled from a server config file. For your clients, this value is received from your server after successful login.
User ID / UUID
User ID is also referred to as UUID
/uuid
in some APIs and server responses but holds the value of the userId
parameter you set during initialization.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
var pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey"
userId: userId
})
pubnub.setFilterExpression("userId != '" + pubnub.getUserId() + "'");
// the userId value is received from your server
var pnconfig = PubNubConfiguration(
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
)
pnconfig.userId: userId
pnconfig.filterExpression: "userId != \(userId)"
var pubnub = PubNub(configuration: pnconfig)
// the uuid value is received from your server
PNConfiguration *pnconfig = [PNConfiguration configurationWithPublishKey:@"myPublishKey"
subscribeKey:@"mySubscribeKey"];
pnconfig.uuid = uuid;
self.pubnub = [PubNub clientWithConfiguration:pnconfig];
NSString *filterExp = [NSString stringWithFormat:@"uuid != '%@'",
self.pubnub.currentConfiguration.uuid];
[self.pubnub setFilterExpression:filterExp];
// the UserId value is received from your server
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
configBuilder.publishKey("myPublishKey");
configBuilder.filterExpression("userId != '" + configBuilder.getUserId() +"'");
PubNub pubNub = PubNub.create(configBuilder.build());
PNConfiguration pnconfig = new PNConfiguration();
pnconfig.PublishKey = "myPublishKey";
pnconfig.SubscribeKey = "mySubscribeKey";
pnconfig.UserId = UserId;
pnconfig.FilterExpression = "UserId != '" + pnconfig.GetCurrentUserId() + "'";
Pubnub pubnub = new Pubnub(pnconfig);
pnconfig = PNConfiguration()
pnconfig.publish_key = "myPublishKey"
pnconfig.subscribe_key = "mySubscribeKey"
pnconfig.user_id = user_id
pnconfig.filter_expression = "user_id !='" + user_id +"'"
pubnub = PubNub(pnconfig)
To learn more about the filter options, refer to the table in the Publish messages section.
Unsubscribe from Channels
Unsubscribe from a channel to stop receiving its messages. You can use this method to unsubscribe from one or more channels.
- JavaScript
- Swift
- Java
- Unity
// create a subscription from a channel entity
const channel = pubnub.channel('channel_1')
const subscription1 = channel.subscription({ receivePresenceEvents: true });
// create a subscription set with multiple channels
const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });
subscription1.subscribe();
subscriptionSet1.subscribe();
subscription1.unsubscribe();
subscriptionSet1.unsubscribe();
let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("channel"),
pubnub.channelGroup("channelGroup"),
pubnub.userMetadata("userMetadataIdentifier")
],
options: ReceivePresenceEvents()
)
let subscription1 = pubnub.channel("channelName").subscription()
subscriptionSet.subscribe()
subscription1.subscribe()
subscriptionSet.unsubscribe()
show all 16 linespubnub.unsubscribe()
.channels(Arrays.asList("ch-1"))
.execute();
pubnub.Unsubscribe<string>()
.Channels(new string[] {
"ch-1"
})
.Execute();
Unsubscribe from all Channels
Use this method to unsubscribe from all channels.
- JavaScript
- Swift
- Java
- Unity
// create a subscription set with multiple channels
const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });
subscriptionSet1.subscribe();
// create a subscription from a channel entity
const channelGroup = pubnub.channelGroup('channelGroup_1')
const subscription1 = channelGroup.subscription({ receivePresenceEvents: true });
subscription1.subscribe();
pubnub.unsubscribeAll();
let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("channel"),
pubnub.channelGroup("channelGroup"),
pubnub.userMetadata("userMetadataIdentifier")
],
options: ReceivePresenceEvents()
)
let subscription1 = pubnub.channel("channelName").subscription()
subscriptionSet.subscribe()
subscription1.subscribe()
pubnub.unsubscribeAll()
pubnub.unsubscribeAll();
pubnub.UnsubscribeAll().Async((result, status) => {
if (!status.Error) {
Debug.Log(result.Message);
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});
Status events
When channels are subscribed, connections are disconnected, reconnected or when connection errors are encountered, status events are generated and clients can receive those events in the listener's status
listener.
Listener
The status listener is the only listener that you add to the pubnub
object, and not to a particular subscription or a subscription set.
Most SDKs provide an operation and category as part of a status event. The supported categories may vary with each language and platform, and some SDKs may have a more robust architecture than others. The differences will be noted as necessary.
Handle Status Events
The event listeners are briefly mentioned in Receive Messages. Compared to other event types, status events are more focused on connection status and subscribe request errors.
- JavaScript
- Swift
- Objective-C
- Java
- C#
- Python
Because the browser can detect when the connection is lost and restored, the JavaScript SDK (when running in a browser) has two additional events that allow you to explicitly handle those scenarios: PNNetworkDownCategory
and PNNetworkUpCategory
. Other environments do not support this real-time network status behavior.
The following data can be extracted from a JavaScript SDK status event.
// add a status listener
pubnub.addListener({
status: (s) => {
console.log('Status', s.category),
}
});
// available data:
// var affectedChannelGroups = event.affectedChannelGroups;
// var affectedChannels = event.affectedChannels;
// var category = event.category;
// var operation = event.operation;
// var lastTimetoken = event.lastTimetoken;
// var currentTimetoken = event.currentTimetoken;
// var subscribedChannels = event.subscribedChannels;
For more details on handling Status Events, visit the JavaScript SDK Status Events documentation page.
The iOS-based SDKs have the most robust status event architecture. There are many more event types that allow you to more explicitly handle each scenario. The following is just a subset of the events which focus on connection and subscribe scenarios.
pubnub.onConnectionStateChange = { newStatus in
print("Connection Status: \(newStatus)")
}
For more details on handling Status Events, visit the Swift SDK Status Events documentation page.
The iOS-based SDKs have the most robust status event architecture. There are many more event types that allow you to more explicitly handle each scenario. The following is just a subset of the events which focus on connection and subscribe scenarios.
While all the status events are passed into the didReceiveStatus
delegate, there are many operations and categories that you can leverage to determine how to handle a given scenario.
[self.pubnub addListener:self];
- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)event {
NSString *operation = event.operation;
NSString *category = event.category;
}
For more details on handling Status Events, visit the Objective-C SDK Status Events documentation page.
pubnub.addListener(new StatusListener() {
@Override
public void status(PubNub pubnub, PNStatus event) {
String operation = event.getOperation();
String category = event.getCategory();
}
});
For more details on handling Status Events, visit the Java SDK Status Events documentation page.
SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
delegate (Pubnub pn, PNStatus e) {
Console.WriteLine("Status event");
}
);
pubnub.AddListener(eventListener)
For more details on handling Status Events, visit the C# SDK Status Events documentation page.
class PrintListener(SubscribeListener):
def status(self, pubnub, status):
print(f'Status:\n{status.__dict__}')
def message(self, pubnub, message):
pass
def presence(self, pubnub, presence):
pass
listener = PrintListener()
pubnub.add_listener(listener)
For more details on handling Status Events, visit the Python SDK Status Events documentation page.