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 user-channel associations, 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.
Add members 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:
You can also use setChannelMembers()
to update the custom metadata for existing channel members.
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;
Remove channel members
You can remove one or more users from a single channel by providing the channel ID and a list of users. The code below deletes the membership to my_channel_2
for the users johndoe_1
and janedoe_1
.
pubnub.objects.removeChannelMembers({
channel: "my_channel_2",
uuids: ["johndoe_1", "janedoe_1"]
}
);
self.client.objects().removeChannelMembers(@"my_channel_2")
.uuids(@[@"johndoe_1", @"janedoe_1"])
.includeFields(PNChannelMemberCustomField | PNChannelMemberUserField)
.performWithCompletion(^(PNManageChannelMembersStatus *status) {
if (!status.isError) {
/**
* Channel's members successfully removed.
* Result object has following information:
* result.data.members - list of channel's existing 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 remove error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.removeChannelMembers()
.channel("my_channel_2")
.uuids(Arrays.asList(PNUUID.uuid("johndoe_1"), PNUUID.uuid("janedoe_1")))
.async(new PNCallback<PNRemoveChannelMembersResult>() {
@Override
public void onResponse(@Nullable final PNRemoveChannelMembersResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
List<string> removeChannelMemberList = new List<string>();
removeChannelMemberList.Add("johndoe_1");
removeChannelMemberList.Add("janedoe_1");
PNResult<PNChannelMembersResult> removeChannelMembersResponse = await pubnub.RemoveChannelMembers()
.Channel("my_channel_2")
.Uuids(removeChannelMemberList)
.Include(new PNChannelMemberField[] { PNChannelMemberField.CUSTOM, PNChannelMemberField.UUID, PNChannelMemberField.UUID_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNChannelMembersResult removeChannelMembersResult = removeChannelMembersResponse.Result;
PNStatus status = removeChannelMembersResponse.Status;
Add channel 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;
Remove channel memberships
You can remove a single user from one or more channels, effectively deleting a membership relation between the user and the channels. The code below removes the current user from the channel my_channel_2
.
pubnub.objects.removeMemberships({
channels: ["my_channel_2"]
});
self.client.objects().removeMemberships()
.uuid(@"uuid")
.channels(@"my_channel_2")
.includeFields(PNMembershipCustomField | PNMembershipChannelField)
.performWithCompletion(^(PNManageMembershipsStatus *status) {
if (!status.isError) {
/**
* UUID's memberships successfully removed.
* 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 remove error. Check 'category' property to find out possible
* issue because of which request did fail.
*
* Request can be resent using: [status retry]
*/
}
});
pubnub.removeMemberships()
.channelMemberships(Collections.singletonList(PNChannelMembership.channel("my_channel_2")))
.async(new PNCallback<PNRemoveMembershipResult>() {
@Override
public void onResponse(@Nullable final PNRemoveMembershipResult result, @NotNull final PNStatus status) {
if (status.isError()) {
//handle error
} else {
//handle result
}
}
});
List<string> removeMembershipList = new List<string>();
if (!string.IsNullOrEmpty(removeMembershipChannelMetaId))
{
removeMembershipList.Add("my_channel_2");
}
PNResult<PNMembershipsResult> removeMembershipsResponse = await pubnub.RemoveMemberships()
.Uuid("uuid")
.Channels(removeMembershipList)
.Include(new PNMembershipField[] { PNMembershipField.CUSTOM, PNMembershipField.CHANNEL, PNMembershipField.CHANNEL_CUSTOM })
.IncludeCount(true)
.ExecuteAsync();
PNMembershipsResult removeMembershipsResult = removeMembershipsResponse.Result;
PNStatus status2 = removeMembershipsResponse.Status;
Membership events
Membership events are generated when memberships are set or removed from the objects database. Object events are disabled by default on new keys. You can enable or disable these events from your key settings in the Admin Portal.
Event | Description | Event channel |
---|---|---|
Membership Set | User-channel association is created or updated. | These events are published on {uuid} and {channel}. |
Membership Removed | User-channel association is deleted. | These events are published on {uuid} and {channel}. |
Membership set event:
{
"channel":"ch-1",
"message":{
"event":"set",
"type":"membership",
"data":{
"channel":{
"id":"ch-1"
},
"uuid":{
"id":"uuid-1"
},
"custom":null,
"updated":"2020-04-17T19:13:59.40962853Z",
"eTag":"AY39mJKK//C0VA"
}
},
"subscription":null,
"timetoken":"15119446002445794"
}
Membership removed event:
{
"channel":"ch-1",
"message":{
"event":"removed",
"type":"membership",
"data":{
"channel":{
"id":"ch-1"
},
"uuid":{
"id":"uuid-1"
},
"custom":null,
"updated":"2020-04-17T19:13:59.40962853Z",
"eTag":"AY39mJKK//C0VA"
}
},
"subscription":null,
"timetoken":"15119446002445794"
}