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.