Manage the user-channel membership relationship

Requires App Context

To set up and manage channel membership, you must enable App Context for your app's keyset in the Admin Portal.

When a user joins a channel or gets invited to it, a membership relationship between that user and the channel is created (Membership entity). The membership ends when this user leaves the channel.

Read on to learn how to check and update user-channel membership.

Get members

getMembers() returns the list of all channel members.

Method signature

This method takes the following parameters:

channel.getMembers(
limit: Int?,
page: PNPage?,
filter: String?,
sort: Collection<PNSortKey<PNMemberKey>> = listOf(),
): PNFuture<MembersResponse>

Input

ParameterTypeRequiredDefaultDescription
limitIntNo100Number of objects to return in response. The default (and maximum) value is 100.
pagePNPageNon/aObject used for pagination to define which previous or next result page you want to fetch.
filterStringNon/aExpression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is defined here.
sortCollection<PNSortKey<PNMemberKey>>NolistOf()A collection to specify the sort order. Available options are id, name, and updated. Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"}. Unless specified otherwise, the items are sorted by the last updated date. Defaults to an empty list.

Output

TypeDescription
PNFuture<MembersResponse>PNFuture containing a set of channel members with membership status, total number of members, and next and prev pages.

Basic usage

List all members of the support channel on the premium support plan.

// reference the "channel" object
chat.getChannel("support").async { result ->
result.onSuccess { channel ->
// get the list of all members with the premium support plan
channel.getMembers(
filter = "custom.support_plan == 'premium'"
).async { membersResult ->
membersResult.onSuccess { membersResponse ->
val membersList = membersResponse.members
// handle success: membersList contains the list of members
}.onFailure { error ->
// handle failure
}
}
}.onFailure { error ->
show all 18 lines

Get membership

getMemberships() returns the list of all channel memberships of a given user.

To get a list of all existing channels, use the getChannels() method.

Method signature

This method takes the following parameters:

user.getMemberships(
limit: Int?,
page: PNPage?,
filter: String?,
sort: Collection<PNSortKey<PNMembershipKey>> = listOf(),
): PNFuture<MembershipsResponse>

Input

ParameterTypeRequiredDefaultDescription
limitIntNo100Number of objects to return in response. The default (and maximum) value is 100.
pagePNPageNon/aObject used for pagination to define which previous or next result page you want to fetch.
filterStringNon/aExpression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is defined here.
sortCollection<PNSortKey<PNMembershipKey>>NolistOf()A collection to specify the sort order. Available options are id, name, and updated. Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"}. Unless specified otherwise, the items are sorted by the last updated date. Defaults to an empty list.

Output

TypeDescription
PNFuture<MembershipsResponse>PNFuture containing a set of memberships, their status and total number, and next and prev pages.

Basic usage

Find out which channels the support_agent_15 user is a member of.

// reference the "support_agent_15" user
chat.getUser("support_agent_15").async { result ->
result.onSuccess { user ->
// get the list of all user memberships
user.getMemberships().async { membershipsResult ->
membershipsResult.onSuccess { membershipsResponse ->
val membershipsList = membershipsResponse.memberships
// handle success: membershipsList contains the list of memberships
}.onFailure { error ->
// handle failure
}
}
}.onFailure { error ->
// handle failure to fetch user
}
show all 16 lines

Get updates

You can receive updates when specific user-channel Membership object(s) are added, edited, or removed using the following methods:

  • streamUpdates() checks updates on a single Membership object and it's tied to an instance of the Membership class.
  • streamUpdatesOn() checks updates on a list of Membership objects and it's tied to the Membership class.

Both methods accept a callback function as an argument. The Chat SDK invokes this callback whenever someone adds, changes, or removes membership data.

Underneath, these methods subscribe the current user to a channel and add an objects event listener to receive all objects events of type membership. These methods also return the unsubscribe function you can invoke to stop receiving objects events and unsubscribe from the channel.

Method signature

These methods take the following parameters:

  • streamUpdates()

    membership.streamUpdates(callback: (membership: Membership?) -> Unit): AutoCloseable
  • streamUpdatesOn()

    class Membership {
    companion object {
    fun streamUpdatesOn(
    memberships: Collection<Membership>,
    callback: (memberships: Collection<Membership>) -> Unit
    ): AutoCloseable
    }
    }

Input

ParameterTypeRequired in streamUpdates()Required in streamUpdatesOn()DefaultDescription
membershipsCollection<Membership>NoYesn/aA collection of Membership objects for which you want to get updates.
callback(membership: Membership?) -> UnitYesNon/aFunction that takes a single Membership object. It defines the custom behavior to be executed when detecting membership changes.
callback(memberships: Collection<Membership>) -> UnitNoYesn/aFunction that takes a set of Membership objects. It defines the custom behavior to be executed when detecting membership changes.

Output

TypeDescription
AutoCloseableInterface that lets you stop receiving membership-related updates (objects events) by invoking the close() method.

Basic usage

Get updates on the first user membership.

  • streamUpdates()

    chat.currentUser.getMemberships().async { result ->
    result.onSuccess { membershipsResponse ->
    // handle success
    val firstMembership = membershipsResponse.memberships.firstOrNull()
    firstMembership?.let {
    val autoCloseable = it.streamUpdates { updatedMembership ->
    if (updatedMembership != null) {
    println("Updated membership: $updatedMembership")
    } else {
    println("Membership update failed or membership doesn't exist.")
    }
    }
    } ?: run {
    println("No memberships found.")
    }
    show all 20 lines

Get updates on the first page of user memberships.

  • streamUpdatesOn()

    chat.currentUser.getMemberships().async { result ->
    result.onSuccess { membershipsResponse ->
    // handle success
    val firstPageMemberships = membershipsResponse.memberships.take(10) // assuming one page has 10 memberships

    val autoCloseable = Membership.streamUpdatesOn(memberships = firstPageMemberships) { updatedMemberships ->
    if (updatedMemberships.isNotEmpty()) {
    updatedMemberships.forEach { updatedMembership ->
    println("Updated membership: $updatedMembership")
    }
    } else {
    println("No membership updates available.")
    }
    }
    }.onFailure { exception ->
    show all 19 lines

Other examples

Stop listening to updates on the first user membership.

  • streamUpdates()

    chat.currentUser.getMemberships().async { result ->
    result.onSuccess { membershipsResponse ->
    // handle success
    val firstMembership = membershipsResponse.memberships.firstOrNull()
    firstMembership?.let {
    val autoCloseable = it.streamUpdates { updatedMembership ->
    if (updatedMembership != null) {
    println("Updated membership: $updatedMembership")
    } else {
    println("Membership update failed or membership doesn't exist.")
    }
    }

    // logic to stop listening to updates can be placed here
    // for example, close `autoCloseable` after some condition or delay
    show all 26 lines

Stop listening to updates on the first page of user memberships.

  • streamUpdatesOn()

    chat.currentUser.getMemberships().async { result ->
    result.onSuccess { membershipsResponse ->
    // handle success
    val firstPageMemberships = membershipsResponse.memberships.take(10) // assuming one page has 10 memberships

    val autoCloseable = Membership.streamUpdatesOn(memberships = firstPageMemberships) { updatedMemberships ->
    if (updatedMemberships.isNotEmpty()) {
    updatedMemberships.forEach { updatedMembership ->
    println("Updated membership: $updatedMembership")
    }
    } else {
    println("No membership updates available.")
    }
    }

    show all 25 lines

Update

update() updates the channel membership information for a given user.

Method signature

This method takes the following parameters:

membership.update(custom: CustomObject): PNFuture<Membership>

Input

ParameterTypeRequiredDefaultDescription
customObjectCustomYesn/aAny custom properties or metadata associated with the channel-user membership in the form of a JSON. Values must be scalar only; arrays or objects are not supported. App Context filtering language doesn’t support filtering by custom properties.

Output

TypeDescription
PNFuture<Membership>Returned (modified) object containing the membership data.

Basic usage

Assign the premium-support role to support_agent_15 on the high-priority-incidents channel.

// get the list of all user memberships and filter out the right channel
user.getMemberships(filter = "channel.id == 'high-priority-incidents'").async {
it.onSuccess { membershipsResponse ->
membershipsResponse
.memberships
.firstOrNull()
// add custom metadata to the user membership
?.update(mapOf("role" to "premium-support"))?.async { membership ->
// ...
}
}.onFailure {
// handle failure
}
}
Last updated on