Code_Function
stringlengths
13
13.9k
Message
stringlengths
10
1.46k
public var activeChannelAction: ChannelAction? by mutableStateOf(null) private set
Currently active channel action, if any. Used to show a dialog for deleting or leaving a channel/conversation.
public val connectionState: StateFlow<ConnectionState> = chatClient.clientState.connectionState
The state of our network connection - if we're online, connecting or offline.
public val user: StateFlow<User?> = chatClient.clientState.user
The state of the currently logged in user.
public val channelMutes: StateFlow<List<ChannelMute>> = chatClient.globalState.channelMutes
Gives us the information about the list of channels mutes by the current user.
private fun buildDefaultFilter(): Flow<FilterObject> { return chatClient.clientState.user.map(Filters::defaultChannelListFilter).filterNotNull() }
Builds the default channel filter, which represents "messaging" channels that the current user is a part of.
public fun isChannelMuted(cid: String): Boolean {return channelMutes.value.any { cid == it.channel.cid }}
Checks if the channel is muted for the current user.
private var queryChannelsState: StateFlow<QueryChannelsState?> = MutableStateFlow(null)
Current query channels state that contains filter, sort and other states related to channels query.
init { if (initialFilters == null) {viewModelScope.launch {val filter = buildDefaultFilter().first()[email protected] = filter}}viewModelScope.launch {init()}}
Combines the latest search query and filter to fetch channels and emit them to the UI.
private suspend fun init() { logger.d { "Initializing ChannelListViewModel" } searchQuery.combine(queryConfigFlow) { query, config -> query to config }.collectLatest { (query, config) ->val queryChannelsRequest = QueryChannelsRequest(filter = createQueryChannelsFilter(config.filters, query),querySort = config.querySort,limit = channelLimit,messageLimit = messageLimit,memberLimit = memberLimit,) logger.d { "Querying channels as state" } queryChannelsState = chatClient.queryChannelsAsState( request = queryChannelsRequest, chatEventHandlerFactory = chatEventHandlerFactory, coroutineScope = viewModelScope, )observeChannels(searchQuery = query)}}
Makes the initial query to request channels and starts observing state changes.
private fun createQueryChannelsFilter(filter: FilterObject, searchQuery: String): FilterObject { return if (searchQuery.isNotEmpty()) {Filters.and(Filter,Filters.or(Filters.and( Filters.autocomplete("member.user.name", searchQuery),Filters.notExists("name")),Filters.autocomplete("name", searchQuery)))} else {filter}}
Creates a filter that is used to query channels. If the [searchQuery] is empty, then returns the original [filter] provided by the user. Otherwise, returns a wrapped [filter] that also checks that the channel name match the [searchQuery].
private suspend fun observeChannels(searchQuery: String) { logger.d { "ViewModel is observing channels. When state is available, it will be notified" }queryChannelsState.filterNotNull().collectLatest { queryChannelsState ->channelMutes.combine(queryChannelsState.channelsStateData, ::Pair).map { (channelMutes, state) ->when (state) {ChannelsStateData.NoQueryActive,ChannelsStateData.Loading,-> channelsState.copy(isLoading = true,searchQuery = searchQuery).also {logger.d { "Loading state for query" }}ChannelsStateData.OfflineNoResults -> {logger.d { "No offline results. Channels are empty" }channelsState.copy(isLoading = false,channelItems = emptyList(),searchQuery = searchQuery)}is ChannelsStateData.Result -> {logger.d { "Received result for state of channels" }channelsState.copy(isLoading = false,channelItems = createChannelItems(state.channels, channelMutes),isLoadingMore = false,endOfChannels = queryChannelsState.endOfChannels.value,searchQuery = searchQuery)}}}.collectLatest { newState -> channelsState = newState }}}
Kicks off operations required to combine and build the [ChannelsState] object for the UI. t connects the 'loadingMore', 'channelsState' and 'endOfChannels' properties from the [queryChannelsState]. @param searchQuery The search query string used to search channels.
public fun selectChannel(channel: Channel?) { this.selectedChannel.value = channel}
Changes the currently selected channel state. This updates the UI state and allows us to observe the state change.
public fun setSearchQuery(newQuery: String) { this.searchQuery.value = newQuery}
Changes the current query state. This updates the data flow and triggers another query operation. The new operation will hold the channels that match the new query.
public fun setFilters(newFilters: FilterObject) {this.filterFlow.tryEmit(value = newFilters)}
Allows for the change of filters used for channel queries.
public fun setQuerySort(querySort: QuerySorter<Channel>) {this.querySortFlow.tryEmit(value = querySort)}
Allows for the change of the query sort used for channel queries.
public fun loadMore() {logger.d { "Loading more channels" }if (chatClient.clientState.isOffline) returnval currentConfig = QueryConfigfilters = filterFlow.value ?: return, querySort = querySortFlow.value)channelsState = channelsState.copy(isLoadingMore = true)val currentQuery = queryChannelsState.value?.nextPageRequest?.value currentQuery?.copy( filter = createQueryChannelsFilter(currentConfig.filters, searchQuery.value),querySort = currentConfig.querySort)?.let { queryChannelsRequest ->chatClient.queryChannels(queryChannelsRequest).enqueue()}}
Loads more data when the user reaches the end of the channels list.
public fun performChannelAction(channelAction: ChannelAction) { if (channelAction is Cancel) {selectedChannel.value = null}activeChannelAction = if (channelAction == Cancel) {null} else { channelAction} }
Clears the active action if we've chosen [Cancel], otherwise, stores the selected action as the currently active action, in [activeChannelAction].
public fun muteChannel(channel: Channel) { dismissChannelAction()  chatClient.muteChannel(channel.type, channel.id).enqueue() }
Mutes a channel.
public fun unmuteChannel(channel: Channel) { dismissChannelAction() chatClient.unmuteChannel(channel.type, channel.id).enqueue() }
Unmutes a channel. @param channel The channel to unmute.
public fun deleteConversation(channel: Channel) { dismissChannelAction() chatClient.channel(channel.cid).delete().toUnitCall().enqueue() }
Deletes a channel, after the user chooses the delete [ChannelAction]. It also removes the [activeChannelAction], to remove the dialog from the UI.
public fun leaveGroup(channel: Channel) { dismissChannelAction()  chatClient.getCurrentUser()?.let { user -> chatClient.channel(channel.type, channel.id).removeMembers(listOf(user.id)).enqueue() } }
Leaves a channel, after the user chooses the leave [ChannelAction]. It also removes the [activeChannelAction], to remove the dialog from the UI.
public fun dismissChannelAction() { activeChannelAction = null selectedChannel.value = null }
Dismisses the [activeChannelAction] and removes it from the UI.
private fun createChannelItems(channels: List<Channel>, channelMutes: List<ChannelMute>): List<ChannelItemState> { val mutedChannelIds = channelMutes.map { channelMute -> channelMute.channel.cid }.toSet() return channels.map { ChannelItemState(it, it.cid in mutedChannelIds) } }
Creates a list of [ChannelItemState] that represents channel items we show in the list of channels.
public val user: StateFlow<User?> = chatClient.clientState.user
The currently logged in user.
public var message: Message by mutableStateOf(Message()) private set
Represents the message that we observe to show the UI data.
public var isShowingOptions: Boolean by mutableStateOf(false) private set
Shows or hides the image options menu and overlay in the UI.
public var isShowingGallery: Boolean by mutableStateOf(false) private set
Shows or hides the image gallery menu in the UI.
init { chatClient.getMessage(messageId).enqueue { result ->if (result.isSuccess) {this.message = result.data()}}}
Loads the message data, which then updates the UI state to shows images.
public fun toggleImageOptions(isShowingOptions: Boolean) {this.isShowingOptions = isShowingOptions}
Toggles if we're showing the image options menu.
public fun toggleGallery(isShowingGallery: Boolean) {this.isShowingGallery = isShowingGallery}
Toggles if we're showing the gallery screen.
public fun deleteCurrentImage(currentImage: Attachment) {val attachments = message.attachmentsval numberOfAttachments = attachments.sizeif (message.text.isNotEmpty() || numberOfAttachments > 1) {val imageUrl = currentImage.assetUrl ?: currentImage.imageUrlval message = message attachments.removeAll { it.assetUrl == imageUrl || it.imageUrl == imageUrl} chatClient.updateMessage(message).enqueue()} else if (message.text.isEmpty() && numberOfAttachments == 1) { chatClient.deleteMessage(message.id).enqueue { result ->if (result.isSuccess) { message = result.data()}}}}
Deletes the current image from the message we're observing, if possible. This will in turn update the UI accordingly or finish this screen in case there are no more images to show.
public var attachmentsPickerMode: AttachmentsPickerMode by mutableStateOf(Images) private set
Currently selected picker mode. [Images], [Files] or [MediaCapture].
public var images: List<AttachmentPickerItemState> by mutableStateOf(emptyList())
List of images available, from the system.
public var files: List<AttachmentPickerItemState> by mutableStateOf(emptyList())
List of files available, from the system.
public var attachments: List<AttachmentPickerItemState> by mutableStateOf(emptyList())
List of attachments available, from the system.
public val hasPickedFiles: Boolean get() = files.any { it.isSelected }
Gives us info if there are any file items that are selected.
public val hasPickedImages: Boolean get() = images.any { it.isSelected }
Gives us info if there are any image items that are selected.
public val hasPickedAttachments: Boolean get() = attachments.any { it.isSelected }
Gives us info if there are any attachment items that are selected.
public var isShowingAttachments: Boolean by mutableStateOf(false) private set
Gives us information if we're showing the attachments picker or not.
public fun loadData() { loadAttachmentsData(attachmentsPickerMode)}
Loads all the items based on the current type.
public fun changeAttachmentPickerMode( attachmentsPickerMode: AttachmentsPickerMode, hasPermission: () -> Boolean = { true },) {this.attachmentsPickerMode = attachmentsPickerMode if (hasPermission()) loadAttachmentsData(attachmentsPickerMode) }
Changes the currently selected [AttachmentsPickerMode] and loads the required data. If no permission is granted will not try and load data to avoid crashes.
public fun changeAttachmentState(showAttachments: Boolean) { isShowingAttachments = showAttachments  if (!showAttachments) {dismissAttachments()}}
Notifies the ViewModel if we should show attachments or not.
private fun loadAttachmentsData(attachmentsPickerMode: AttachmentsPickerMode) { if (attachmentsPickerMode == Images) {val images = storageHelper.getMedia().map { AttachmentPickerItemState(it, false) } this.images = images this.attachments = images this.files = emptyList() } else if (attachmentsPickerMode == Files) {val files = storageHelper.getFiles().map { AttachmentPickerItemState(it, false) } this.files = files this.attachments = files this.images = emptyList() } }
Loads the attachment data, based on the [AttachmentsPickerMode].
public fun changeSelectedAttachments(attachmentItem: AttachmentPickerItemState) { val dataSet = attachments val itemIndex = dataSet.indexOf(attachmentItem) val newFiles = dataSet.toMutableList() val newItem = dataSet[itemIndex].copy(isSelected = !newFiles[itemIndex].isSelected) newFiles.removeAt(itemIndex)  newFiles.add(itemIndex, newItem) if (attachmentsPickerMode == Files) { files = newFiles } else if (attachmentsPickerMode == Images) { images = newFiles } attachments = newFiles }
Triggered when an [AttachmentMetaData] is selected in the list. Added or removed from the corresponding list, be it [files] or [images], based on [attachmentsPickerMode].
public fun getSelectedAttachments(): List<Attachment> { val dataSet = if (attachmentsPickerMode == Files) files else images val selectedAttachments = dataSet.filter { it.isSelected } return storageHelper.getAttachmentsForUpload(selectedAttachments.map { it.attachmentMetaData }) }
Loads up the currently selected attachments. It uses the [attachmentsPickerMode] to know which attachments to use - files or images. It maps all files to a list of [Attachment] objects, based on their type.
public fun getAttachmentsFromUris(uris: List<Uri>): List<Attachment> { return storageHelper.getAttachmentsFromUris(uris) }
Transforms selected file Uris to a list of [Attachment]s we can upload.
public fun getAttachmentsFromMetaData(metaData: List<AttachmentMetaData>): List<Attachment> { return storageHelper.getAttachmentsForUpload(metaData) }
Transforms the selected meta data into a list of [Attachment]s we can upload.
public fun dismissAttachments() { attachmentsPickerMode = Images images = emptyList() files = emptyList() }
Triggered when we dismiss the attachments picker. We reset the state to show images and clear the items for now, until the user needs them again.
private val channelState: StateFlow<ChannelState?> = chatClient.watchChannelAsState( cid = channelId, messageLimit = messageLimit, coroutineScope = viewModelScope)
Holds information about the current state of the [Channel].
private val ownCapabilities: StateFlow<Set<String>> = channelState.filterNotNull().flatMapLatest { it.channelData }.map { it.ownCapabilities }.stateIn(scope =viewModelScope,started = SharingStarted.Eagerly,initialValue = setOf())
Holds information about the abilities the current user is able to exercise in the given channel.
public val currentMessagesState: MessagesState get() = if (isInThread) threadMessagesState else messagesState
State handler for the UI, which holds all the information the UI needs to render messages. It chooses between [threadMessagesState] and [messagesState] based on if we're in a thread or not.
private var messagesState: MessagesState by mutableStateOf(MessagesState())
State of the screen, for [MessageMode.Normal].
private var threadMessagesState: MessagesState by mutableStateOf(MessagesState())
State of the screen, for [MessageMode.MessageThread].
public var messageMode: MessageMode by mutableStateOf(MessageMode.Normal) private set
Holds the current [MessageMode] that's used for the messages list. [MessageMode.Normal] by default.
public var channel: Channel by mutableStateOf(Channel()) private set
The information for the current [Channel].
public var typingUsers: List<User> by mutableStateOf(emptyList()) private set
The list of typing users.
public var messageActions: Set<MessageAction> by mutableStateOf(mutableSetOf()) private set
Set of currently active [MessageAction]s. Used to show things like edit, reply, delete and similar actions.
public val isInThread: Boolean get() = messageMode is MessageMode.MessageThread
Gives us information if we're currently in the [Thread] message mode.
public val isShowingOverlay: Boolean get() = messagesState.selectedMessageState != null || threadMessagesState.selectedMessageState != null
Gives us information if we have selected a message.
public val connectionState: StateFlow<ConnectionState> by chatClient.clientState::connectionState
Gives us information about the online state of the device.
public val isOnline: Flow<Boolean> get() = chatClient.clientState.connectionState.map { it == ConnectionState.CONNECTED }
Gives us information about the online state of the device.
public val user: StateFlow<User?> get() = chatClient.clientState.user
Gives us information about the logged in user state.
private var threadJob: Job? = null
[Job] that's used to keep the thread data loading operations. We cancel it when the user goes out of the thread state.
private var lastLoadedMessage: Message? = null
Represents the last loaded message in the list, for comparison when determining the [NewMessageState] for the screen.
private var lastLoadedThreadMessage: Message? = null
Represents the last loaded message in the thread, for comparison when determining the NewMessage
private var lastSeenChannelMessage: Message? by mutableStateOf(null)
Represents the latest message we've seen in the channel.
private var lastSeenThreadMessage: Message? by mutableStateOf(null)
Represents the latest message we've seen in the active thread.
private var scrollToMessage: Message? = null
Represents the message we wish to scroll to.
private val logger = StreamLog.getLogger("Chat:MessageListViewModel")
Instance of [TaggedLogger] to log exceptional and warning cases in behavior.
init { observeTypingUsers() observeMessages() observeChannel()}
Sets up the core data loading operations - such as observing the current channel and loading messages and other pieces of information.
private fun observeMessages() { viewModelScope.launch { channelState.filterNotNull().collectLatest { channelState ->combine(channelState.messagesState, user, channelState.reads) { state, user, reads -> when (state) { is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.NoQueryActive,is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.Loading, -> messagesState.copy(isLoading = true) is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.OfflineNoResults -> messagesState.copy( isLoading = false, messageItems = emptyList(), ) is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.Result -> { messagesState.copy( isLoading = false, messageItems = groupMessages( messages = filterMessagesToShow(state.messages), isInThread = false, reads = reads, ), isLoadingMore = false, endOfMessages = channelState.endOfOlderMessages.value, currentUser = user, ) } } } .catch { it.cause?.printStackTrace() showEmptyState() } .collect { newState -> val newLastMessage = (newState.messageItems.firstOrNull { it is MessageItemState } as? MessageItemState)?.message val hasNewMessage = lastLoadedMessage != null && messagesState.messageItems.isNotEmpty() && newLastMessage?.id != lastLoadedMessage?.id messagesState = if (hasNewMessage) { val newMessageState = getNewMessageState(newLastMessage, lastLoadedMessage) newState.copy( newMessageState = newMessageState, unreadCount = getUnreadMessageCount(newMessageState) ) } else { newState }  messagesState.messageItems.firstOrNull { it is MessageItemState && it.message.id == scrollToMessage?.id }?.let { focusMessage((it as MessageItemState).message.id) }  lastLoadedMessage = newLastMessage } } } }
Starts observing the messages in the current channel. We observe the 'messagesState', 'user' and endOfOlderMessages' states, as well as build the `newMessageState` using [getNewMessageState] and combine it into a [MessagesState] that holds all the information required for the screen.
private fun observeTypingUsers() { viewModelScope.launch { channelState.filterNotNull().flatMapLatest { it.typing }.collect { typingUsers = it.users }} }
Starts observing the list of typing users.
private fun observeChannel() { viewModelScope.launch {channelState.filterNotNull().flatMapLatest { state  >combine(state.channelData,state.membersCount,state.watcherCount,) { _, _, _ ->state.toChannel()}}.collect { channel  >chatClient.notifications.dismissChannelNotifications(channelType = channel.type,channelId = channel.id)setCurrentChannel(channel)}}}
Starts observing the current [Channel] created from [ChannelState]. It emits new data when either channel data, member count or online member count updates.
private fun setCurrentChannel(channel: Channel) { this.channel = channel }
Sets the current channel, used to show info in the UI.
private fun filterMessagesToShow(messages: List<Message>): List<Message> { val currentUser = user.value return messages.filter { val shouldShowIfDeleted = when (deletedMessageVisibility) { DeletedMessageVisibility.ALWAYS_VISIBLE -> true DeletedMessageVisibility.VISIBLE_FOR_CURRENT_USER -> { !(it.deletedAt != null && it.user.id != currentUser?.id) } else -> it.deletedAt == null } val isSystemMessage = it.isSystem() || it.isError()  shouldShowIfDeleted || (isSystemMessage && showSystemMessages) } }
Used to filter messages which we should show to the current user.
private fun getNewMessageState(lastMessage: Message?, lastLoadedMessage: Message?): NewMessageState? { val currentUser = user.value  return if (lastMessage != null && lastLoadedMessage != null && lastMessage.id != lastLoadedMessage.id) { if (lastMessage.user.id == currentUser?.id) { MyOwn } else { Other } } else { null } }
Builds the [NewMessageState] for the UI, whenever the message state changes. This is used to allow us to show the user a floating button giving them the option to scroll to the bottom when needed.
private fun getUnreadMessageCount(newMessageState: NewMessageState? = currentMessagesState.newMessageState): Int { if (newMessageState == null || newMessageState == MyOwn) return 0  val messageItems = currentMessagesState.messageItems val lastSeenMessagePosition = getLastSeenMessagePosition(if (isInThread) lastSeenThreadMessage else lastSeenChannelMessage) var unreadCount = 0  for (i in 0..lastSeenMessagePosition) { val messageItem = messageItems[i]  if (messageItem is MessageItemState && !messageItem.isMine && messageItem.message.deletedAt == null) { unreadCount++ } }  return unreadCount }
Counts how many messages the user hasn't read already. This is based on what the last message they've seen is, and the current message state.
private fun getLastSeenMessagePosition(lastSeenMessage: Message?): Int { if (lastSeenMessage == null) return 0  return currentMessagesState.messageItems.indexOfFirst { it is MessageItemState && it.message.id == lastSeenMessage.id } }
Gets the list position of the last seen message in the list.
public fun updateLastSeenMessage(message: Message) { val lastSeenMessage = if (isInThread) lastSeenThreadMessage else lastSeenChannelMessage  if (lastSeenMessage == null) { updateLastSeenMessageState(message) return }  if (message.id == lastSeenMessage.id) { return }  val lastSeenMessageDate = lastSeenMessage.createdAt ?: Date() val currentMessageDate = message.createdAt ?: Date() if (currentMessageDate < lastSeenMessageDate) { return } updateLastSeenMessageState(message) } 
Attempts to update the last seen message in the channel or thread. We only update the last seen message the first time the data loads and whenever we see a message that's newer than the current last seen message.
private fun updateLastSeenMessageState(currentMessage: Message) { if (isInThread) { lastSeenThreadMessage = currentMessage  threadMessagesState = threadMessagesState.copy(unreadCount = getUnreadMessageCount()) } else { lastSeenChannelMessage = currentMessage  messagesState = messagesState.copy(unreadCount = getUnreadMessageCount()) }  val (channelType, id) = channelId.cidToTypeAndId()  val latestMessage: MessageItemState? = currentMessagesState.messageItems.firstOrNull { messageItem -> messageItem is MessageItemState } as? MessageItemState  if (currentMessage.id == latestMessage?.message?.id) { chatClient.markRead(channelType, id).enqueue() } }
Updates the state of the last seen message. Updates corresponding state based on [isInThread].
private fun showEmptyState() { messagesState = messagesState.copy(isLoading = false, messageItems = emptyList()) }
If there's an error, we just set the current state to be empty - 'isLoading' as false and 'messages' as an empty list.
public fun loadMore() { if (chatClient.clientState.isOffline) return val messageMode = messageMode  if (messageMode is MessageMode.MessageThread) { threadLoadMore(messageMode) } else { messagesState = messagesState.copy(isLoadingMore = true) chatClient.loadOlderMessages(channelId, messageLimit).enqueue() } }
Triggered when the user loads more data by reaching the end of the current messages.
private fun threadLoadMore(threadMode: MessageMode.MessageThread) { threadMessagesState = threadMessagesState.copy(isLoadingMore = true) if (threadMode.threadState != null) { chatClient.getRepliesMore( messageId = threadMode.parentMessage.id, firstId = threadMode.threadState?.oldestInThread?.value?.id ?: threadMode.parentMessage.id, limit = DefaultMessageLimit, ).enqueue() } else { threadMessagesState = threadMessagesState.copy(isLoadingMore = false) logger.w { "Thread state must be not null for offline plugin thread load more!" } } }
Load older messages for the specified thread [MessageMode.MessageThread.parentMessage].
private fun loadMessage(message: Message) { val cid = channelState.value?.cid if (cid == null || chatClient.clientState.isOffline) return  chatClient.loadMessageById(cid, message.id).enqueue() }
Loads the selected message we wish to scroll to when the message can't be found in the current list.
public fun selectMessage(message: Message?) { if (message != null) {changeSelectMessageState(if (message.isModerationFailed(chatClient)) {SelectedMessageFailedModerationState(message = message,ownCapabilities = ownCapabilities.value)} else {SelectedMessageOptionsState(message = message,ownCapabilities = ownCapabilities.value)})}}
Triggered when the user long taps on and selects a message.
public fun selectReactions(message: Message?) {if (message != null) {changeSelectMessageState(SelectedMessageReactionsState(message = message,ownCapabilities = ownCapabilities.value))}}
Triggered when the user taps on and selects message reactions.
public fun selectExtendedReactions(message: Message?) {if (message != null) {changeSelectMessageState(SelectedMessageReactionsPickerState(message = message,ownCapabilities = ownCapabilities.value))}}
Triggered when the user taps the show more reactions button.
private fun changeSelectMessageState(selectedMessageState: SelectedMessageState) {if (isInThread) {threadMessagesState = threadMessagesState.copy(selectedMessageState = selectedMessageState)} else {messagesState = messagesState.copy(selectedMessageState = selectedMessageState)}}
Changes the state of [threadMessagesState] or [messagesState] depending on the thread mode.
public fun openMessageThread(message: Message) {loadThread(message)}
Triggered when the user taps on a message that has a thread active.
private fun loadThread(parentMessage: Message) {val threadState = chatClient.getRepliesAsState(parentMessage.id, DefaultMessageLimit)val channelState = channelState.value ?: returnmessageMode = MessageMode.MessageThread(parentMessage, threadState)observeThreadMessages(threadId = threadState.parentId,messages = threadState.messages,endOfOlderMessages = threadState.endOfOlderMessages,reads = channelState.reads)}
Changes the current [messageMode] to be [Thread] with [ThreadState] and Loads thread data using ChatClient directly. The data is observed by using [ThreadState].
private fun observeThreadMessages( threadId: String,messages: StateFlow<List<Message>>,endOfOlderMessages: StateFlow<Boolean>,reads: StateFlow<List<ChannelUserRead>>,) {threadJob = viewModelScope.launch {combine(user, endOfOlderMessages, messages, reads) { user, endOfOlderMessages, messages, reads ->threadMessagesState.copy(isLoading = false,messageItems = groupMessages(messages = filterMessagesToShow(messages),isInThread = true,reads = reads,),isLoadingMore = false,endOfMessages = endOfOlderMessages,currentUser = user,parentMessageId = threadId)}.collect { newState ->val newLastMessage =(newState.messageItems.firstOrNull { it is MessageItemState } as? MessageItemState)?.messagethreadMessagesState = newState.copy(newMessageState getNewMessageState(newLastMessage, lastLoadedThreadMessage))lastLoadedThreadMessage = newLastMessage}}}
Observes the currently active thread. In process, this creates a [threadJob] that we can cancel once we leave the thread.
private fun groupMessages(messages: List<Message>,isInThread: Boolean,reads: List<ChannelUserRead>,): List<MessageListItemState> {val parentMessageId =(messageMode as? MessageMode.MessageThread)?.parentMessage?.idval currentUser = user.valueval groupedMessages = mutableListOf<MessageListItemState>()val lastRead = reads.filter { it.user.id != currentUser?.id }.mapNotNull { it.lastRead }.maxOrNull() messages.forEachIndexed { index, message ->val user = message.user val previousMessage = messages.getOrNull(index - 1) val nextMessage = messages.getOrNull(index + 1) val previousUser = previousMessage?.user val nextUser = nextMessage?.user val willSeparateNextMessage = nextMessage?.let { shouldAddDateSeparator(message, it) } ?: false  val position = when { previousUser != user && nextUser == user && !willSeparateNextMessage -> MessageItemGroupPosition.Top previousUser == user && nextUser == user && !willSeparateNextMessage -> MessageItemGroupPosition.Middle previousUser == user && nextUser != user -> MessageItemGroupPosition.Bottom else -> MessageItemGroupPosition.None }  val isLastMessageInGroup = position == MessageItemGroupPosition.Bottom || position == MessageItemGroupPosition.None  val shouldShowFooter = messageFooterVisibility.shouldShowMessageFooter( message = message, isLastMessageInGroup = isLastMessageInGroup, nextMessage = nextMessage )  if (shouldAddDateSeparator(previousMessage, message)) { groupedMessages.add(DateSeparatorState(message.getCreatedAtOrThrow())) }  if (message.isSystem() || message.isError()) { groupedMessages.add(SystemMessageState(message = message)) } else { val isMessageRead = message.createdAt ?.let { lastRead != null && it <= lastRead } ?: false  groupedMessages.add( MessageItemState( message = message, currentUser = currentUser, groupPosition = position, parentMessageId = parentMessageId, isMine = user.id == currentUser?.id, isInThread = isInThread, isMessageRead = isMessageRead, shouldShowFooter = shouldShowFooter, deletedMessageVisibility = deletedMessageVisibility ) ) }  if (index == 0 && isInThread) { groupedMessages.add(ThreadSeparatorState(message.replyCount)) } }  return groupedMessages.reversed() }
Takes in the available messages for a [Channel] and groups them based on the sender ID. We put the message in a group, where the positions can be [MessageItemGroupPosition.Top], [MessageItemGroupPosition.Middle],  [MessageItemGroupPosition.Bottom] or [MessageItemGroupPosition.None] if the message isn't in a group.
private fun shouldAddDateSeparator(previousMessage: Message?, message: Message): Boolean { return if (!showDateSeparators) { false } else if (previousMessage == null) { true } else { val timeDifference = message.getCreatedAtOrThrow().time - previousMessage.getCreatedAtOrThrow().time  return timeDifference > dateSeparatorThresholdMillis } }
Decides if we need to add a date separator or not.
@JvmOverloads @Suppress("ConvertArgumentToSet") public fun deleteMessage(message: Message, hard: Boolean = false) { messageActions = messageActions - messageActions.filterIsInstance<Delete>() removeOverlay()  chatClient.deleteMessage(message.id, hard).enqueue() }
Removes the delete actions from our [messageActions], as well as the overlay, before deleting the selected message.
@Suppress("ConvertArgumentToSet") public fun flagMessage(message: Message) { messageActions = messageActions - messageActions.filterIsInstance<Flag>() removeOverlay()  chatClient.flagMessage(message.id).enqueue() }
Removes the flag actions from our [messageActions], as well as the overlay, before flagging  the selected message.
private fun resendMessage(message: Message) { val (channelType, channelId) = message.cid.cidToTypeAndId()  chatClient.sendMessage(channelType, channelId, message).enqueue() }
Retries sending a message that has failed to send.
private fun copyMessage(message: Message) { clipboardHandler.copyMessage(message) }
Copies the message content using the [ClipboardHandler] we provide. This can copy both attachment and text messages.
private fun updateUserMute(user: User) { val isUserMuted = chatClient.globalState.muted.value.any { it.target.id == user.id }  if (isUserMuted) { unmuteUser(user.id) } else { muteUser(user.id) } }
Mutes or unmutes the user that sent a particular message.
public fun muteUser( userId: String, timeout: Int? = null, ) { chatClient.muteUser(userId, timeout) .enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: "Unable to mute the user" StreamLog.e("MessageListViewModel.muteUser") { errorMessage } }) }
Mutes the given user inside this channel.
public fun unmuteUser(userId: String) { chatClient.unmuteUser(userId) .enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: "Unable to unmute the user"  StreamLog.e("MessageListViewModel.unMuteUser") { errorMessage } }) }
Unmutes the given user inside this channel.