Unread messages
The Unread Message Count feature shows users how many messages they missed while offline. Once they reconnect or log into the app again, they can get the number of messages published in a given channel while they were gone.
Chat SDK stores info about the timetoken of the last message the current user read on a given channel on the lastReadMessageTimetoken property. lastReadMessageTimetoken is available on the Membership object.
This property is automatically set for a user when they first join (join()) a given channel or are invited to it (invite() and inviteMultiple()). For all further updates of this property, you must decide what user actions will trigger methods that mark messages as read in your chat app - whether that's some user interaction on UI, like scrolling, your app going offline, or any other behavior.
Requires App Context and Message Persistence
To store message timetokens on the user-channel membership relationship at PubNub, you must enable App Context and Message Persistence for your app's keyset in the Admin Portal.
Get last read message
You can access the lastReadMessageTimetoken property of the Membership object to check what is the timetoken of the last message a user read on a given channel. lastReadMessageTimetoken returns the last read message timetoken stored in the membership data between the channel and the current user. Use it to display markers on the message list denoting which messages haven't been read by the user yet.
Sample code
Get the timetoken of the last message read by the support_agent_15 user on the support channel.
1chat.getUser("support_agent_15").async { result ->
2 result.onSuccess { user ->
3 user?.getMemberships(filter = "channel.id == 'support'")?.async { membershipsResult ->
4 membershipsResult.onSuccess { membershipsResponse ->
5 val membership = membershipsResponse.memberships.firstOrNull()
6 println("Last read message timetoken: ${membership?.lastReadMessageTimetoken}")
7 }.onFailure {
8 // handle failure
9 }
10 }
11 }.onFailure {
12 // handle failure
13 }
14}
Get unread messages count (one channel)
getUnreadMessagesCount() returns the number of messages you didn't read on a given channel.
This includes all messages published after your last read timetoken, including messages sent by yourself and all other channel members. The method cannot filter messages by sender - it counts all unread messages regardless of who published them. You can display this number on UI in the channel list of your chat app.
Method signature
This method has the following signature:
1membership.getUnreadMessagesCount(): PNFuture<Long?>
Input
This method doesn't take any parameters.
Output
| Type | Description |
|---|---|
PNFuture<Long?> | Retrieves from Message Persistence the number (count) of all messages unread by a given user on a given channel from the last read message. The method returns null when there is no last read message timetoken set on the Message object. |
Sample code
Get the number of all messages unread by the support_agent_15 user on the support channel.
1// get the details of the "support_agent_15" user
2chat.getUser("support_agent_15").async { userResult ->
3 userResult.onSuccess { user ->
4 user?.getMemberships(filter = "channel.id == 'support'")?.async { membershipsResult ->
5 membershipsResult.onSuccess { membershipsResponse ->
6 val membership = membershipsResponse.memberships.firstOrNull()
7 membership?.getUnreadMessagesCount()?.async { unreadCountResult ->
8 unreadCountResult.onSuccess { unreadCount ->
9 if (unreadCount != null) {
10 println("Unread messages count: $unreadCount")
11 } else {
12 println("No unread messages count available.")
13 }
14 }.onFailure {
15 // handle failure
show all 25 linesGet unread messages count (all channels)
fetchUnreadMessagesCounts() returns info on all messages you didn't read on joined channels that have unread messages.
This method only returns channels with unread message counts greater than 0 - channels with zero unread messages are filtered out. For each returned channel, this includes all messages published after your last read timetoken, including messages sent by yourself and all other channel members. While you can filter which channels to get unread counts for using the filter parameter (e.g., by channel type, membership status, or custom properties), the message count within each channel includes all messages after the last read timetoken regardless of who published them. You can display these counts in the UI in the channel list of your chat app.
The response includes pagination tokens that allow you to fetch more results if needed.
Unread counts and filtering
fetchUnreadMessagesCounts uses the Memberships API. Filters here may target channel.* fields only (plus common fields: status, type, custom). You can't use uuid.* fields.
Unread counts always include all messages published after your last read timetoken including messages you sent yourself. You can't filter unread counts by sender but you can query Message Persistence from the last read timetoken and filter client-side.
See filterable fields: • Memberships filters • Members filters
Method signature
This method has the following signature:
1chat.fetchUnreadMessagesCounts(
2 limit: Int? = null,
3 page: PNPage? = null,
4 filter: String? = null,
5 sort: Collection<PNSortKey<PNMembershipKey>> = listOf()
6): PNFuture<UnreadMessagesCounts>
Input
| Parameter | Description |
|---|---|
limitType: IntDefault: null | Number of objects to return in response. The default (and maximum) value is 100. |
pageType: PNPageDefault: null | Object used for pagination to define which previous or next result page you want to fetch. |
filterType: String (Memberships filter)Default: null | Filter expression evaluated against channel memberships only. Allowed targets: channel.* plus common fields (status, type, custom). uuid.* fields aren't supported. |
sortType: Collection<PNSortKey<PNMembershipKey>>Default: listOf() | Key-value pair of a property to sort by, and a sort direction. 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"}. By default, the items are sorted by the last updated date. |
Output
| Parameter | Description |
|---|---|
PNFuture<UnreadMessagesCounts>Type: object | Returned object containing these fields: countsByChannel and page. |
→ countsByChannelType: Array<object> | Array of objects containing channel, membership, and count information. |
→ channelType: Channel | Channel with unread messages. |
→ membershipType: Membership | Returned Membership object showing the user-channel data. |
→ countType: number | Total number of messages unread by the current user on a given channel. |
→ pageType: object | Object containing pagination information. |
→ nextType: string | undefined | Token for fetching the next page of results. |
→ prevType: string | undefined | Token for fetching the previous page of results. |
Sample code
Get the number of all messages unread by the support_agent_15 user on all joined channels.
1// reference the "support_agent_15" user
2chat.getUser("support_agent_15").async { result ->
3 result.onSuccess { user ->
4 user?.let {
5 // get all messages unread by that user
6 chat.fetchUnreadMessagesCounts().async { unreadResult ->
7 unreadResult.onSuccess { unreadMessagesCounts ->
8 // access the counts for each channel
9 val countsByChannel = unreadMessagesCounts.countsByChannel
10
11 // access pagination tokens if needed
12 val next = unreadMessagesCounts.page.next
13 val prev = unreadMessagesCounts.page.prev
14 }.onFailure {
15 // handle failure
show all 22 linesTo avoid counting your own recently sent messages as unread, ensure your app updates the last read timetoken.
Mark messages as read (one channel)
setLastReadMessage() and setLastReadMessageTimetoken() let you set the timetoken of the last read message on a given channel to set a timeline from which you can count unread messages. You choose on your own which user action it is bound to.
Setting the last read message for users lets you implement the Read Receipts feature and monitor which channel member read which message.
Method signature
These methods take the following parameters:
-
setLastReadMessage()1membership.setLastReadMessage(message: Message): PNFuture<Membership> -
setLastReadMessageTimetoken()1membership.setLastReadMessageTimetoken(timetoken: Long): PNFuture<Membership>
Input
| Parameter | Required by setLastReadMessage() | Required by setLastReadMessageTimetoken() | Description |
|---|---|---|---|
messageType: MessageDefault: n/a | Yes | No | Last read message on a given channel with the timestamp that gets added to the user-channel membership as the lastReadMessageTimetoken property. |
timetokenType: LongDefault: n/a | No | Yes | Timetoken of the last read message on a given channel that gets added to the user-channel membership as the lastReadMessageTimetoken property. |
Output
| Type | Description |
|---|---|
PNFuture<Membership> | Returned Membership object updated with the lastReadMessageTimetoken parameter. |
Sample code
Set the message with the 16200000000000001 timetoken as the last read message for the support_agent_15 user on the support channel.
-
setLastReadMessage()
show all 30 lines1// retrieve the "support_agent_15" user
2chat.getUser("support_agent_15").async { userResult ->
3 userResult.onSuccess { user ->
4 // retrieve membership details for the "support" channel
5 user?.getMemberships(filter = "channel.id == 'support'")?.async { membershipsResult ->
6 membershipsResult.onSuccess { membershipsResponse ->
7 val membership = membershipsResponse.memberships.firstOrNull()
8 // retrieve the specific message with the given timetoken
9 chat.getChannel("support").getMessage(16200000000000001).async { messageResult ->
10 messageResult.onSuccess { message ->
11 // Set the last read message
12 membership?.setLastReadMessage(message)?.async { setResult ->
13 setResult.onSuccess {
14 // handle success
15 }.onFailure { -
setLastReadMessageTimetoken()
show all 23 lines1// retrieve the "support_agent_15" user
2chat.getUser("support_agent_15").async { userResult ->
3 userResult.onSuccess { user ->
4 // retrieve membership details for the "support" channel
5 user?.getMemberships(filter = "channel.id == 'support'")?.async { membershipsResult ->
6 membershipsResult.onSuccess { membershipsResponse ->
7 val membership = membershipsResponse.memberships.firstOrNull()
8 // set the last read message timetoken
9 membership?.setLastReadMessageTimetoken(16200000000000001)?.async { setResult ->
10 setResult.onSuccess {
11 // handle success
12 }.onFailure {
13 // handle failure
14 }
15 }
Mark messages as read (all channels)
markAllMessagesAsRead() lets you mark as read all messages you didn't read on all joined channels.
Method signature
This method has the following signature:
1chat.markAllMessagesAsRead(
2 limit: Int?,
3 page: PNPage?,
4 filter: String?,
5 sort: Collection<PNSortKey<PNMembershipKey>> = listOf()
6): PNFuture<MarkAllMessageAsReadResponse>
Input
| Parameter | Description |
|---|---|
limitType: IntDefault: 100 | Number of objects to return in response. The default (and maximum) value is 100. |
pageType: PNPageDefault: n/a | Object used for pagination to define which previous or next result page you want to fetch. |
filterType: StringDefault: n/a | Expression used to filter the results. Returns only these messages whose properties satisfy the given expression. The filter language is defined here. |
sortType: Collection<PNSortKey<PNMembershipKey>>Default: listOf() | Key-value pair of a property to sort by, and a sort direction. 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"}. By default, the items are sorted by the last updated date. |
Output
| Type | Description |
|---|---|
PNFuture<MarkAllMessageAsReadResponse> | Returned object with a list of memberships and these fields: next, prev, total, and status. |
Sample code
Mark the total number of 50 messages as read and specify you want to fetch the results from the next page using a string that was previously returned from the PubNub server.
1val nextPageString: String = "your_next_page_string"
2
3chat.markAllMessagesAsRead(
4 limit = 50,
5 page = PNPage(nextPageString, null)
6).async { result ->
7 result.onSuccess {
8 // handle success
9 }.onFailure {
10 // handle failure
11 }
12}
Get unread messages count (all channels) (deprecated)
Deprecated
The getUnreadMessagesCounts() method is deprecated. Use fetchUnreadMessagesCounts() instead.
getUnreadMessagesCounts() returns info on all messages you didn't read on joined channels that have unread messages.
This method only returns channels with unread message counts greater than 0 - channels with zero unread messages are filtered out. For each returned channel, this includes all messages published after your last read timetoken, including messages sent by yourself and all other channel members. The method cannot filter messages by sender - it counts all unread messages regardless of who published them. You can display this number on UI in the channel list of your chat app.
Method signature
This method has the following signature:
1chat.getUnreadMessagesCounts(
2 limit: Int?,
3 page: PNPage?,
4 filter: String?,
5 sort: Collection<PNSortKey<PNMembershipKey>> = listOf()
6): PNFuture<Set<GetUnreadMessagesCounts>>
Input
| Parameter | Description |
|---|---|
limitType: IntDefault: 100 | Number of objects to return in response. The default (and maximum) value is 100. |
pageType: PNPageDefault: n/a | Object used for pagination to define which previous or next result page you want to fetch. |
filterType: StringDefault: n/a | Expression used to filter which channel memberships to include in the results. Returns unread message counts only for channels whose membership properties satisfy the given expression. The filter language is defined here. |
sortType: Collection<PNSortKey<PNMembershipKey>>Default: listOf() | Key-value pair of a property to sort by, and a sort direction. 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"}. By default, the items are sorted by the last updated date. |
Output
| Type | Description |
|---|---|
PNFuture<Set<GetUnreadMessagesCounts>> | PNFuture containing the number (count) of all messages unread by a given user on all joined channels after the last read message. It returns these details: channel, membership, count. |
Sample code
Get the number of all messages unread by the support_agent_15 user on all joined channels.
1// reference the "chat" object and invoke the "getUser()" method
2chat.getUser("support_agent_15").async { result ->
3 result.onSuccess { user ->
4 user?.let {
5 chat.getUnreadMessagesCounts(
6 filter = "user.id == 'support_agent_15'"
7 ).async { unreadMessagesResult ->
8 unreadMessagesResult.onSuccess { unreadMessagesCounts ->
9 // handle success
10 unreadMessagesCounts.forEach { unreadCount ->
11 println("Channel: ${unreadCount.channelId}, Unread messages count: ${unreadCount.count}")
12 }
13 }.onFailure {
14 // handle failure
15 }
show all 21 lines