Channel subscriptions

Users can subscribe to channels and begin listening for messages on a single socket connection. You can subscribe to a list of up to 100 channels, or use channel groups to subscribe to the list of channels in a channel group.

Subscribing to channels initiates a real-time connection with PubNub. This connection stays open as long as the user remains subscribed from a client application. Any user subscribing to a channel receives messages in under 100ms, regardless of which global region the message was published in.

Subscriptions vs memberships

A subscription isn't the same as a membership: subscriptions allow you to send and receive messages on channels, whereas memberships are metadata about the relationship between users and channels.

Subscribe to channels

The following code samples show a client subscribing to a single channel called chats.room1.

pubnub.subscribe({
channels: ['ch-1'],
withPresence: true,
});

Typically, you subscribe to channels on app load. As a user moves around in the app, they stay subscribed to their list of channels so they can continue to receive messages on all their channels.

Subscribe to channel groups

Channel groups are useful in case users in your application need to subscribe to more than 100 channels at a time. Your application can create a channel group that holds up to 2,000 channels. Each user can now subscribe to up to 10 channel groups for a total of up to 20,000 channels.

Channel Group operations

You can't publish to a Channel Group. You can only subscribe to it. To publish within Channel Group, you need to publish to each channel individually.

pubnub.subscribe({
channelGroups: ["cg_user123"],
withPresence: true
});

Managing channel groups

To use a Channel Group, there is just one additional step: add channels to a channel group.

Adding channels to a channel group also creates the channel group if it doesn't already exist. Your server can add 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.

pubnub.channelGroups.addChannels({
channels: ["chats.room1", "chats.room2", "alerts.system"]
channelGroup: "cg_user123"
},
function(status) {
console.log(status);
}
);
Last updated on