/ SDKs / Android
SDKs
Chat SDKs Android v4
Chat SDKs Android
Chat SDKs
Android
Version 4

Collection migration guide

Copy link

Sendbird Chat SDK v4 for Android has introduced group channel collection and message collection to enhance efficiency and improve developer experience. This guide assists you in transitioning from low-level interface implementations to more efficient, collection-based solutions. We strongly recommend integrating collections into your existing codebase for improved efficiency and user experience.

Key benefits of using collection

Copy link
  1. View-driven interface: The collection interface organizes handler methods and event callbacks around the currently displayed view. Event callbacks are triggered only for the channels or messages that are currently being displayed.

  2. Effortless event handling: By assigning a collection handler, the data source for your channel and message views are automatically updated when an event is triggered. You can set your handler, and the collection handles the event updates to your data source.

  3. Automated updates upon reconnection: Collections handle channel and message updates automatically upon app reconnection, eliminating the need for manual intervention.

  4. Local caching capabilities: Collections also handle local caching of chat data for offline messaging.


Implementing group channel collection

Copy link

The following section further explains how to implement and use group channel collection.

Step 1 Create a group channel collection instance

Copy link

To use the group channel collection interfaces, a GroupChannelCollection instance must be created first.

class GroupChannelListActivity: Activity() {
    lateinit var collection: GroupChannelCollection
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        createGroupChannelCollection()
    }

    private fun createGroupChannelCollection() {
        // First, create a GroupChannelListQuery instance.
        val query = GroupChannel.createMyGroupChannelListQuery(
            GroupChannelListQueryParams().apply {
                includeEmpty = true
                order = GroupChannelListQueryOrder.LATEST_LAST_MESSAGE
                includeMetadata = true
                includeFrozen = true
                // You can add other params setters.
            }
        )

        this.collection = SendbirdChat.createGroupChannelCollection(
            GroupChannelCollectionCreateParams(query)
        )
    }
}

Step 2 Retrieve a list of group channels

Copy link

You can load more channels by using the loadMore(GroupChannelsCallbackHandler) method of GroupChannelCollection created in step 1. You don't need to create a GroupChannelListQuery instance and utilize the query to load the next page anymore.

With collectionWithout collection
class GroupChannelListActivity: Activity() {
    lateinit var collection: GroupChannelCollection
    val channels: MutableList<GroupChannel> = mutableListOf()

    // ...

    fun loadMore() {
        if (collection.hasMore) {
            collection.loadMore { channels, e ->
                when {
                    e != null -> {
                        // Handle error.
                    }
                    channels != null -> {
                        // Add channels to your data source.
                        this.channels.addAll(channels)
                    }
                }
            }
        }
    }
}

Step 3 Handle group channel events

Copy link

With collections, numerous group channel event callbacks have been consolidated into three streamlined GroupChannelCollectionHandler methods. The new methods are designed to only pass events that are relevant to the group channel list view.

Example

Copy link

You're managing the channel list view and want to show a typing indicator when a member starts typing and update the last message in real-time.

Before collections, you had to implement different GroupChannelHandler methods to keep up with these changes.

With group channel collection, however, all changes from events are already applied to channels in the onChannelsUpdated(GroupChannelContext, List<GroupChannel> method method. Now, all you need to do is refresh your channel list with the updated channels as shown in the example code below.

With collectionWithout collection
class GroupChannelListActivity: Activity() {
    lateinit var collection: GroupChannelCollection
    val channels: MutableList<GroupChannel> = mutableListOf()
    val groupChannelCollectionHandler = object : GroupChannelCollectionHandler {
        override fun onChannelsAdded(context: GroupChannelContext, channels: List<GroupChannel>) {
            [email protected](channels)
            // Refresh added channel's view.
        }

        override fun onChannelsUpdated(context: GroupChannelContext, channels: List<GroupChannel>) {
            // channels carries latest typing status and last message for channels that have had updates.
            // Refresh updated channel's view.
        }

        override fun onChannelsDeleted(
            context: GroupChannelContext,
            deletedChannelUrls: List<String>
        ) {
            [email protected] { it.url in deletedChannelUrls }
            // Refresh deleted channel's view.
        }
    }
}

Handle specific events

Copy link

To react to specific events, such as when a member starts typing, check ChannelContext.source in onChannelsUpdated(GroupChannelContext, List<GroupChannel>). The following code is an example of triggering an alert when a member starts typing.

class GroupChannelListActivity: Activity() {
    lateinit var collection: GroupChannelCollection
    val channels: MutableList<GroupChannel> = mutableListOf()
    val groupChannelCollectionHandler = object : GroupChannelCollectionHandler {
        // ...
        override fun onChannelsUpdated(context: GroupChannelContext, channels: List<GroupChannel>) {
            when (context.collectionEventSource) {
                CollectionEventSource.EVENT_TYPING_STATUS_UPDATED -> updateTypingIndicator()
            }
        }
        // ...
    }
    
    fun updateTypingIndicator() {
        println("Someone started typing!")
    }
}

To learn more, see a full list of CollectionEventSource.

Step 4 Keep cached channels synced with the Sendbird server

Copy link

When a user is online, all data associated with the group channels they are a member of are automatically updated. However, when a user is disconnected from the Sendbird server and reconnects later, data associated with group channels need to be updated.

Previously, you had to call SendbirdChat.getMyGroupChannelChangeLogsByTimestamp(Long, GroupChannelChangeLogsParams(), GroupChannelChangeLogsHandler) or SendbirdChat.getMyGroupChannelChangeLogsByToken(String, GroupChannelChangeLogsParams(), GroupChannelChangeLogsHandler) to manually update the data upon reconnection.

With collections, however, it automatically keeps your cached channels' information up-to-date without requiring additional code implementation. If you wish to be notified when this update is completed in order to do any custom updates, you can check CollectionEventSource.CHANNEL_CHANGELOG inside each GroupChannelCollectionHandler method.

With collectionWithout collection
class GroupChannelListActivity: Activity() {
    lateinit var collection: GroupChannelCollection
    val channels: MutableList<GroupChannel> = mutableListOf()
    val groupChannelCollectionHandler = object : GroupChannelCollectionHandler {
        override fun onChannelsAdded(context: GroupChannelContext, channels: List<GroupChannel>) {
            when (context.collectionEventSource) {
                CollectionEventSource.CHANNEL_CHANGELOG -> {
                    // Handle added channels here.
                }
            }
        }

        override fun onChannelsUpdated(context: GroupChannelContext, channels: List<GroupChannel>) {
            when (context.collectionEventSource) {
                CollectionEventSource.CHANNEL_CHANGELOG -> {
                    // Handle updated channels here.
                }
            }
        }

        override fun onChannelsDeleted(
            context: GroupChannelContext,
            deletedChannelUrls: List<String>
        ) {
            when (context.collectionEventSource) {
                CollectionEventSource.CHANNEL_CHANGELOG -> {
                    // handle deleted channels here.
                }
            }
        }
    }
}

Implementing message collection

Copy link

The following section explains how to implement and use message collection.

Step 1 Create a message collection instance

Copy link

To use message collection interfaces, a MessageCollection instance must be created first. You can do so by calling the SendbirdChat.createMessageCollection(MessageCollectionCreateParams) method. Then, you must start the collection to load the first batch of messages through messageCollection.initialize(MessageCollectionInitPolicy, MessageCollectionInitHandler?).

class MessageListActivity : Activity() {
    lateinit var collection: MessageCollection
    lateinit var channel: GroupChannel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        createMessageCollection()
        initializeCollection()
    }

    fun createMessageCollection() {
        val params = MessageListParams().apply {
            reverse = false
            inclusive = false
            messageTypeFilter = MessageTypeFilter.ALL
            messagePayloadFilter = MessagePayloadFilter(
                includeMetaArray = true,
                includeReactions = true
            )
        }

        this.collection = SendbirdChat.createMessageCollection(
            MessageCollectionCreateParams(channel, params)
        )
    }

    fun initializeCollection() {
        collection.initialize(
            MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API,
            object : MessageCollectionInitHandler {
                override fun onCacheResult(cachedList: List<BaseMessage>?, e: SendbirdException?) {
                    // Messages are retrieved from the local cache.
                    // They might be too outdated compared to startingPoint.
                }

                override fun onApiResult(apiResultList: List<BaseMessage>?, e: SendbirdException?) {
                    // Messages are retrieved from the Sendbird server through the API.
                    // According to MessageCollectionInitPolicy.cacheAndReplaceByApi,
                    // the existing data source needs to be cleared
                    // before adding retrieved messages to the local cache.
                }
            }
        )
    }
}

Step 2 Retrieve a list of messages

Copy link

You can load more messages by using the hasNext or hasPrevious method of MessageCollection created in step 1. Previously, you had to call either getMessagesByTimestamp(Long, MessageListParams, BaseMessagesHandler) or getMessagesByMessageId(Long, MessageListParams, BaseMessagesHandler) and manually manage the data source for the message list after loading.

With collectionWithout collection
// GroupChannelView

val messages: MutableList<BaseMessage> = mutableListOf()
fun loadMore() {
    if (collection.hasNext) {
        collection.loadNext { messages, e ->
            when {
                messages != null -> this.messages.addAll(messages)
                e != null -> { 
                  // Handle error.
                }
            }
        }
    }

    if (collection.hasPrevious) {
        collection.loadPrevious { messages, e ->
            when {
                messages != null -> this.messages.addAll(messages)
                e != null -> { 
                  // Handle error.
                }
            }
        }
    }
}

Step 3 Handle channel events

Copy link

With collections, numerous message event callbacks have been consolidated into six streamlined MessageCollectionHandler methods. Step 3 explains how to handle events on the currently displayed group channel.

Example of group channel event

Copy link

If you wanted to handle events when new members join or leave a channel, you had to implement two separate GroupChannelHandler methods shown in the code below to handle the events. With message collection, however, all changes from both events are already applied to the channel parameter in the onMessagesUpdated(MessageContext, GroupChannel, List<BaseMessage>). All you need to do is refresh with the updated channels as shown in the example code below.

With collectionWithout collection
class MessageListActivity : Activity() {
    val messageCollectionHandler = object : MessageCollectionHandler {
        override fun onMessagesUpdated(
            context: MessageContext,
            channel: GroupChannel,
            messages: List<BaseMessage>
        ) {
            // Update channel with latest member data.
        }
    }
}

Handle specific events

Copy link

For use cases where you need to specifically check whether a member has joined or left a channel separately, you can check ChannelContext.source in channelCollection(_:context:updatedChannels:).

class MessageListActivity : Activity() {
    val messageCollectionHandler = object : MessageCollectionHandler {
        override fun onMessagesUpdated(
            context: MessageContext,
            channel: GroupChannel,
            messages: List<BaseMessage>
        ) {
            when (context.collectionEventSource) {
                CollectionEventSource.EVENT_USER_JOINED -> {
                    // Handle a user joined event.
                }
                
                CollectionEventSource.EVENT_USER_LEFT -> {
                    // Handle a user left event.
                }
            }
        }
    }
}

To learn more, see a full list of CollectionEventSource.

Step 4 Handle message events

Copy link

With collection, you can set the UserMessageHandler as null and listen to changes to the message collection using the onMessagesAdded(MessageContext, GroupChannel, List<BaseMessage>) method of MessageCollectionHandler. Through the handler method, message events are handled accordingly depending on their message status. This allows you to send a message and track their statuses separately, making it easier to manage your implementation.

With collectionWithout collection
fun sendUserMessage() {
    val params = UserMessageCreateParams(message = "Hello, World!")
    channel.sendUserMessage(params, null)
}

override fun onMessagesAdded(
    context: MessageContext,
    channel: GroupChannel,
    messages: List<BaseMessage>
) {
    when (context.messagesSendingStatus) {
        SendingStatus.PENDING -> {
            // Add pending messages to your data source.
        }
        
        SendingStatus.FAILED -> {
            // Add failed messages to your data source.
        }
        
        SendingStatus.SUCCEEDED -> {
            // Add succeeded messages to your data source.
        }
    }
}
override fun onMessagesUpdated(
    context: MessageContext,
    channel: GroupChannel,
    messages: List<BaseMessage>
) {
    when (context.messagesSendingStatus) {
        SendingStatus.SUCCEEDED -> {
        }
        SendingStatus.FAILED -> { // (pending -> failed)
        }
        SendingStatus.CANCELED -> { // (pending -> canceled)
        }
    }
}

Other message events

Copy link

Previously, different events that affect your message list data had to be handled separately. For example, to update your message list data with the latest message update events, reaction events, and poll update events, you had to use three different GroupChannelHandler handler methods - channel(_:didUpdate:), channel(_:updatedReaction:), and channel(_:didUpdatePoll:). In each, you had to separately implement how to handle your message list.

Using message collection, you can handle all message events by simply updating your message data through updatedMessages of onMessagesUpdated(MessageContext,GroupChannel,List<BaseMessage>) handler. This is because updatedMessages already carries all the updated information from each message update, reaction, and poll update event.

With collectionWithout collection
override fun onMessagesUpdated(
    context: MessageContext,
    channel: GroupChannel,
    messages: List<BaseMessage>
) {
    // updatedMessages already carries all latest information from message update, reaction, and poll update events.
    // Update your message list data source.
}

Handle specific events

Copy link

To react to specific events, such as displaying an alert when a poll has been updated, check MessageContext.source.

override fun onMessagesUpdated(
    context: MessageContext,
    channel: GroupChannel,
    messages: List<BaseMessage>
) {
    when (context.collectionEventSource) {
        CollectionEventSource.EVENT_POLL_UPDATED -> {
            // Update poll.
        }
    }
}

To learn more, see a full list of CollectionEventSource.

Step 5 Keep cached channel and messages synced with the Sendbird server

Copy link

When a user is online, all data associated with the group channels they are a member of and its messages are automatically updated. However, when a user is disconnected from the Sendbird server and reconnects later, data associated with group channels need to be updated.

Refresh cached channel upon reconnection

Copy link

With message collection, it automatically keeps your cached channel information up-to-date without requiring additional code implementation.

// Previously, you had to call `channel.refresh(completionHandler)` 
// to manually update the data upon reconnection.
class MessageListActivity : Activity() {
    lateinit var channel: GroupChannel
    val connectionHandler = object : ConnectionHandler {
        override fun onReconnectSucceeded() {
            channel.refresh { e ->
                if (e != null) {
                    // Handle error.
                }

                // Channel is refreshed to the latest info.
            }
        }
    }
}

Refresh cached messages upon reconnection

Copy link

Previously, to keep your cached messages up-to-date, you had to manually call either channel.getMessageChangeLogsSinceTimestamp(Long, MessageChangeLogsParams, GetMessageChangeLogsHandler) or channel.getMessageChangeLogsSinceToken(String, MessageChangeLogsParams, GetMessageChangeLogsHandler) upon reconnection to the Sendbird server.

With message collection, however, it automatically fetches the changelogs of message internally. Then, it passes the results onto onMessagesUpdated(MessageContext, GroupChannel, List<BaseMessage>) or onMessagesDeleted(MessageContext, GroupChannel, List<BaseMessage>) with context.collectionEventSource set as CollectionEventSource.MESSAGE_CHANGELOG.

With collectionWithout collection
class MessageListActivity : Activity() {
    lateinit var channel: GroupChannel
    val messageCollectionHandler = object : MessageCollectionHandler {
        override fun onMessagesAdded(
            context: MessageContext,
            channel: GroupChannel,
            messages: List<BaseMessage>
        ) {
            when (context.collectionEventSource) {
                CollectionEventSource.MESSAGE_FILL, CollectionEventSource.MESSAGE_CHANGELOG -> {
                    // Add messages.
                }
            }
        }

        override fun onMessagesUpdated(
            context: MessageContext,
            channel: GroupChannel,
            messages: List<BaseMessage>
        ) {
            when (context.collectionEventSource) {
                CollectionEventSource.MESSAGE_CHANGELOG -> {
                    // Update messages.
                }
            }
        }

        override fun onMessagesDeleted(
            context: MessageContext,
            channel: GroupChannel,
            messages: List<BaseMessage>
        ) {
            when (context.collectionEventSource) {
                CollectionEventSource.MESSAGE_CHANGELOG -> {
                    // Delete messages.
                }
            }
        }
    }   
}

Collection event sources

Copy link

The following table shows a list of CollectionEventSources that trigger GroupChannelCollectionHandler and MessageCollectionHandler methods to be called. The event sources are passed to ChannelContext and MessageContext inside handler methods.

NameEvent description

EVENT_MESSAGE_RECEIVED

A message has been received in a group channel.

EVENT_MESSAGE_UPDATED

A message has been updated in a group channel.

EVENT_MENTION

A user has been mentioned in a message sent in a group channel.

EVENT_USER_MUTED

A user has been muted in a group channel.

EVENT_USER_UNMUTED

A user has been unmuted in a group channel.

EVENT_USER_BANNED

A user has been banned from a group channel.

EVENT_USER_UNBANNED

A user has been unbanned from a group channel.

EVENT_CHANNEL_FROZEN

A group channel has been frozen.

EVENT_CHANNEL_UNFROZEN

A group channel has been unfrozen.

EVENT_CHANNEL_CHANGED

A group channel has the following changes:
- The last message has been updated.
- Unread count has been updated.
- A new message has been pinned.
- A group channel has been unhidden.

EVENT_CHANNEL_DELETED

A group channel has been deleted.

EVENT_MESSAGE_DELETED

A message has been deleted in a group channel.

EVENT_CHANNEL_METADATA_CREATED

Metadata for a group channel has been created.

EVENT_CHANNEL_METADATA_UPDATED

Metadata for a group channel has been updated.

EVENT_CHANNEL_METADATA_DELETED

Metadata for a group channel has been deleted.

EVENT_CHANNEL_METACOUNTER_CREATED

A metacounter for a group channel has been created.

EVENT_CHANNEL_METACOUNTER_UPDATED

A metacounter for a group channel has been updated.

EVENT_CHANNEL_METACOUNTER_DELETED

A metacounter for a group channel has been deleted.

EVENT_REACTION_UPDATED

A message reaction has been updated.

EVENT_OPERATOR_UPDATED

A channel operator has been updated.

EVENT_THREAD_INFO_UPDATED

A reply message has been created or deleted from a thread in a group channel.

EVENT_READ_STATUS_UPDATED

A message has been read by a reader who is not the currentUser.

EVENT_DELIVERY_STATUS_UPDATED

The delivery status of a message sent to a group channel has been updated.

EVENT_TYPING_STATUS_UPDATED

A user starts typing a message to a group channel.

EVENT_CHANNEL_MEMBER_COUNT_CHANGED

The member count of one or more group channels has changed.

EVENT_USER_RECEIVED_INVITATION

A user has been invited to a group channel.

EVENT_USER_DECLINED_INVITATION

A user has declined an invitation to a group channel.

EVENT_USER_JOINED

A user has joined a group channel.

EVENT_USER_LEFT

A user has left a group channel.

EVENT_CHANNEL_HIDDEN

A group channel has been hidden.

EVENT_PINNED_MESSAGE_UPDATED

A message has been pinned or unpinned in a group channel.

EVENT_POLL_UPDATED

A poll has been updated in a group channel.

EVENT_POLL_VOTED

A user has voted on a poll in a group channel.

MESSAGE_CHANGELOG

Message changelog has been received.

MESSAGE_FILL

A message gap has been filled.

CHANNEL_CHANGELOG

Channel changelog has been received.

LOCAL_MESSAGE_PENDING_CREATED

A pending message has been created.

LOCAL_MESSAGE_FAILED

A message has failed to send.

LOCAL_MESSAGE_CANCELED

A message has been canceled.

LOCAL_MESSAGE_RESEND_STARTED

A failed message has been resent in a group channel.

CHANNEL_REFRESH

A group channel has been refreshed through startMessageCollection() method.

EVENT_MESSAGE_SENT

A message has been sent in a group channel.

POLL_CHANGELOG

Poll changelog has been received.