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.
Refer to Channel Membership to learn more about working with channel metadata.
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.
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.
- JavaScript
- Swift
- Objective-C
- C#
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 User ID \(response.memberships)")
if let nextPage = response.next {
print("The next page used for pagination: \(nextPage)")
}
case let .failure(error):
show all 18 linesNSArray<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 - Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
show all 27 linesList<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
.
- JavaScript
- Objective-C
- Java
- C#
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 - Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
* result.data.prev - Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data.
* result.data.totalCount - Total number of channel's members.
*/
} else {
/**
show all 22 linespubnub.removeChannelMembers()
.channel("my_channel_2")
.uuids(Arrays.asList(PNUUID.uuid("johndoe_1"), PNUUID.uuid("janedoe_1")))
.async(result -> { /* check 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:
- JavaScript
- Swift
- Objective-C
- C#
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 User ID \(response.memberships)")
if let nextPage = response.next {
print("The next page used for pagination: \(nextPage)")
}
case let .failure(error):
show all 18 linesNSArray<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.
show all 30 linesList<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
.
- JavaScript
- Objective-C
- Java
- C#
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 - Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
* status.data.prev - Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data.
* status.data.totalCount - Total number of UUID's memberships.
*/
} else {
show all 23 linespubnub.removeMemberships()
.channelMemberships(Collections.singletonList(PNChannelMembership.channel("my_channel_2")))
.async(result -> { /* check 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"
show all 20 linesMembership 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"
show all 20 lines