stability improvements and race conditions

This commit is contained in:
Diogo
2024-11-01 18:20:05 +00:00
parent 99719088e5
commit f197c4174c
4 changed files with 12 additions and 2 deletions
@@ -331,6 +331,7 @@ object ChatModel {
if (chatId.value == cInfo.id) {
// Prevent situation when chat item already in the list received from backend
if (chatItems.value.none { it.id == cItem.id }) {
chatItemsSectionArea[cItem.id] = ChatSectionArea.Bottom
if (chatItems.value.lastOrNull()?.id == ChatItem.TEMP_LIVE_CHAT_ITEM_ID) {
chatItems.add(kotlin.math.max(0, chatItems.value.lastIndex), cItem)
} else {
@@ -379,6 +380,7 @@ object ChatModel {
} else {
cItem
}
chatItemsSectionArea[ci.id] = ChatSectionArea.Bottom
chatItems.add(ci)
true
}
@@ -610,6 +612,7 @@ object ChatModel {
val cItem = ChatItem.liveDummy(chatInfo is ChatInfo.Direct)
withContext(Dispatchers.Main) {
chatItems.add(cItem)
chatItemsSectionArea[cItem.id] = ChatSectionArea.Bottom
}
return cItem
}
@@ -617,6 +620,7 @@ object ChatModel {
fun removeLiveDummy() {
if (chatItems.value.lastOrNull()?.id == ChatItem.TEMP_LIVE_CHAT_ITEM_ID) {
chatItems.removeLast()
chatItemsSectionArea.remove(ChatItem.TEMP_LIVE_CHAT_ITEM_ID)
}
}
@@ -261,17 +261,23 @@ suspend fun apiLoadBottomSection(chatInfo: ChatInfo, rhId: Long?) {
withContext(Dispatchers.Main) {
val updatedItems = chatModel.chatItems.value.toMutableStateList()
var insertIndex = updatedItems.size
var needsMerge = false
for (cItem in chat.first.chatItems.asReversed()) {
if (chatModel.chatItemsSectionArea[cItem.id] == null) {
updatedItems.add(insertIndex, cItem)
chatModel.chatItemsSectionArea[cItem.id] = ChatSectionArea.Bottom
} else {
needsMerge = true
chatModel.chatItemsSectionArea[cItem.id] = ChatSectionArea.Bottom
insertIndex = max(0, insertIndex - 1)
}
}
if (needsMerge) {
updatedItems.associateTo(chatModel.chatItemsSectionArea) { it.id to ChatSectionArea.Bottom }
}
chatModel.chatItems.replaceAll(updatedItems)
}
}
@@ -1005,7 +1005,7 @@ fun BoxScope.ChatItemsList(
LaunchedEffect(Unit) {
launch {
snapshotFlow { chatModel.chatId.value }
snapshotFlow { chatInfoUpdated.value.id }
.distinctUntilChanged()
.collect {
if (revealedItems.value.isNotEmpty()) {
@@ -229,7 +229,7 @@ fun openLoadedChat(chat: Chat, chatModel: ChatModel, landingSection: ChatLanding
chatModel.chatItems.replaceAll(chat.chatItems)
chatModel.chatId.value = chat.chatInfo.id
chatModel.chatItemsSectionArea.clear()
chat.chatItems.associateTo(chatModel.chatItemsSectionArea) { it.id to landingSectionToArea(landingSection) }
chatModel.chatItems.value.associateTo(chatModel.chatItemsSectionArea) { it.id to landingSectionToArea(landingSection) }
}
suspend fun apiLoadMessages(