Managing Channel Memberships
PubNub allows you to store the association between users and channels so clients can get channel memberships for a user, or show members in a channel. Memberships are metadata, not subscriptions. Users don't need to join a channel to subscribe and start exchanging messages on it, but it can be a helpful mechanism for your application to use.
Clients can receive events to get notified when users are added or removed from a channel, and there's a full list of membership operations at the end of this page.
There are two ways to associate a user with a channel:
- Add the user to the channel's list of members
- Add the channel to the user's list of memberships
The end result is the same—an association between user and channel is stored in the database, and you can retrieve it in the future—but each approach serves a different purpose.
Add users to a channel
To add one or more users to a single channel, as you might do when adding a new team channel, add those users to the channel's members with setChannelMembers()
, like so:
pubnub.objects.setChannelMembers({
channel: "channel-1",
uuids: [
"johndoe_1",
{ id: "janedoe_1", custom: { trialPeriod: true } },
],
});
let newMembership = PubNubMembershipMetadataBase(
uuidMetadataId: "janedoe_1", channelMetadataId: "channel-1"
)
pubnub.setMemberships(
channel: newMembership.channelMetadataId,
uuids: [newMembership]
) { result in
switch result {
case let .success(response):
print("The channel memberships for the uuid \(response.memberships)")
if let nextPage = response.next {
print("The next page used for pagination: \(nextPage)")
}
case let .failure(error):
print("Update Memberships request failed with error: \(error.localized### Description)")
}
}
NSArray<NSDictionary *> *uuids = @[
@{ @"uuid": @"johndoe_1" }
@{ @"uuid": @"janedoe_1", @"custom": @{ @"trialPeriod": @YES } }
];
self.client.objects().setChannelMembers(@"channel-1")
.uuids(uuids)
.includeFields(PNChannelMemberCustomField | PNChannelMemberUserField)
.performWithCompletion(^(PNManageChannelMembersStatus *status) {
if (!status.isError) {
/**
* Channel's members successfully set.
* Result object has following information:
* result.data.members - list of existing channel's members,
* result.data.next - cursor bookmark for fetching the next page,
* result.data.prev - cursor bookmark for fetching the previous page,
* result.data.totalCount - total number of channel's members.
*/
} else {
/**
* Handle channel's members set error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
List<PNChannelMember> setMemberChannelList = new List<PNChannelMember>();
if (!string.IsNullOrEmpty(setMemberChUuid))
{
setMemberChannelList.Add(new PNChannelMember() { Uuid = "johndoe_1" } );
setMemberChannelList.Add(new PNChannelMember() { Uuid = "janedoe_1", Custom = new Dictionary<string, object>() { { "trialPeriod", true } } });
}
PNResult<PNChannelMembersResult> setChannelMembersResponse = await pubnub.SetChannelMembers()
.Channel(setmemberChMetadataId)
.Uuids(setMemberChannelList)
.Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNChannelMembersResult setChannelMembersResult = setChannelMembersResponse.Result;
PNStatus status2 = setChannelMembersResponse.Status;
You can also use setChannelMembers()
to update the custom metadata for existing channel members.
PubNub generates a "Membership Set" event when a member is added to a channel. Refer to Receive membership events for details.
Add channels to a user's memberships
To add one user to several channels, perhaps as part of a new-user onboarding process, add those channels to the user's memberships with setMemberships()
, like so:
pubnub.objects.setMemberships({
channels: [ "channel-1", { id: "channel-2", custom: { starred: true } }]
});
let newMembership = PubNubMembershipMetadataBase(
uuidMetadataId: "my_user", channelMetadataId: "channel-1"
)
pubnub.setMemberships(
uuid: newMembership.uuidMetadataId,
channels: [newMembership]
) { result in
switch result {
case let .success(response):
print("The channel memberships for the uuid \(response.memberships)")
if let nextPage = response.next {
print("The next page used for pagination: \(nextPage)")
}
case let .failure(error):
print("Update Memberships request failed with error: \(error.localized### Description)")
}
}
NSArray<NSDictionary *> *channels = @[
@{ @"channel": @"channel-1" },
@{ @"channel": @"channel-2", @"custom": @{ @"starred": @YES } }
];
self.client.objects().setMemberships()
.uuid(@"uuid")
.channels(channels)
.includeCount(YES)
.limit(40)
.includeFields(NMembershipCustomField | PNMembershipChannelField)
.performWithCompletion(^(PNManageMembershipsStatus *status) {
if (!status.isError) {
/**
* UUID's memberships successfully set.
* Result object has following information:
* status.data.memberships - list of UUID's existing memberships,
* status.data.next - cursor bookmark for fetching the next page,
* status.data.prev - cursor bookmark for fetching the previous page,
* status.data.totalCount - total number of UUID's memberships.
*/
} else {
/**
* Handle UUID's memberships set error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
List<PNMembership> setMembershipChannelMetadataIdList = new List<PNMembership>();
if (!string.IsNullOrEmpty(seMembershipChannelMetaId))
{
setMembershipChannelMetadataIdList.Add(new PNMembership() { Channel = "channel-1" });
setMembershipChannelMetadataIdList.Add(new PNMembership() { Channel = "channel-2", Custom = new Dictionary<string, object>() { { "starred", true } } });
}
PNResult<PNMembershipsResult> setMembershipsResponse = await pubnub.SetMemberships()
.Uuid("my-uuid")
.Channels(setMembershipChannelMetadataIdList)
.Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNMembershipsResult setMembershipsResult = setMembershipsResponse.Result;
PNStatus status = setMembershipsResponse.Status;
PubNub generates a "Membership Set" event when a membership is set for a user. Refer to Receive membership events for details.
Receive membership events
PubNub generates events as memberships change:
- Membership Set: a membership is set for a user, or a member is added to a channel
- Membership Deleted: a membership is removed for a user, or a user is removed from a channel
Membership events for each user are published to a channel named for each user. For example, to receive events for the user with UUID chat-user-9A7X8
, you would subscribe to the channel named chat-user-9A7X8
.
Refer to Adding a listener for details on receiving these events with the objects
listener.
Membership management operations
Membership management operates from one of two perspectives: that of the user, or that of the channel.
User-focused membership operations are:
- Add a channel to the user's memberships:
addMemberships()
- Remove a channel from the user's memberships:
removeMemberships()
- List the user's channel memberships:
getMemberships()
Channel-focused membership operations are:
- Add users to the channel's members:
setChannelMembers()
- Remove users from the channel's members:
removeChannelMembers()
- List the channel's members:
getChannelMembers()