Skip to content

Commit f4fcd2c

Browse files
committed
fix:修改使用uuid作为协议中的seqId;修复聊天界面聊天记录读取出错的问题。
1 parent a4bc4e5 commit f4fcd2c

File tree

4 files changed

+87
-95
lines changed

4 files changed

+87
-95
lines changed

AndroidJetpackComposeSample/IMChatComponent/src/main/java/com/nxg/im/chat/component/conversation/ConversationChatViewModel.kt

+10-18
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.nxg.im.chat.component.conversation
22

3-
import android.util.Log
43
import androidx.lifecycle.ViewModel
54
import androidx.lifecycle.viewModelScope
65
import androidx.paging.Pager
@@ -19,7 +18,6 @@ import kotlinx.coroutines.Dispatchers
1918
import kotlinx.coroutines.flow.MutableStateFlow
2019
import kotlinx.coroutines.flow.StateFlow
2120
import kotlinx.coroutines.flow.asStateFlow
22-
import kotlinx.coroutines.flow.collect
2321
import kotlinx.coroutines.launch
2422

2523

@@ -43,22 +41,7 @@ class ConversationChatViewModel : ViewModel(), SimpleLogger {
4341
// The UI collects from this StateFlow to get its state updates
4442
val uiState: StateFlow<ConversationChatUiState> = _uiState.asStateFlow()
4543

46-
val messagePager = Pager(
47-
config = PagingConfig(pageSize = 50)
48-
) {
49-
KtChatDatabase.getInstance(Utils.getApp()).messageDao().pagingSource()
50-
}
51-
52-
init {
53-
viewModelScope.launch {
54-
55-
messagePager.flow.collect {
56-
57-
logger.debug { "loadConversationChat messagePager.flow update " }
58-
59-
}
60-
}
61-
}
44+
var messagePager: Pager<Int, Message>? = null
6245

6346
/**
6447
* 创建会话(从通信点击进入聊天的情况需要创建会话)
@@ -136,7 +119,16 @@ class ConversationChatViewModel : ViewModel(), SimpleLogger {
136119
)
137120
)
138121
)
122+
messagePager = Pager(config = PagingConfig(pageSize = 50)) {
123+
KtChatDatabase.getInstance(Utils.getApp()).messageDao()
124+
.pagingSource(
125+
fromId = friend.friendId,
126+
toId = it.user.uuid,
127+
chatType
128+
)
129+
}
139130
}
131+
140132
}
141133
}
142134
}

AndroidJetpackComposeSample/IMChatComponent/src/main/java/com/nxg/im/chat/component/conversation/KtChatConversationChat.kt

+56-53
Original file line numberDiff line numberDiff line change
@@ -499,72 +499,75 @@ private val KtChatJumpToBottomThreshold = 56.dp
499499
@SuppressLint("CoroutineCreationDuringComposition")
500500
@Composable
501501
fun KtChatIMMessages(
502-
pager: Pager<Int, Message>,
502+
pager: Pager<Int, Message>? = null,
503503
me: User,
504504
friend: Friend,
505505
onAuthorClick: (String) -> Unit,
506506
resend: (Message) -> Unit = {},
507507
scrollState: LazyListState,
508508
modifier: Modifier = Modifier
509509
) {
510-
val lazyPagingItems = pager.flow.collectAsLazyPagingItems()
511-
var itemCount by remember { mutableStateOf(lazyPagingItems.itemCount) }
512-
val scope = rememberCoroutineScope()
513-
Box(modifier = modifier) {
514-
LazyColumn(
515-
reverseLayout = true,
516-
state = scrollState,
517-
modifier = Modifier
518-
.testTag(ConversationTestTag)
519-
.fillMaxWidth()
520-
.wrapContentHeight()
521-
) {
522-
itemsIndexed(
523-
items = lazyPagingItems,
524-
// The key is important so the Lazy list can remember your
525-
// scroll position when more items are fetched!
526-
key = { _, message -> message.id }
527-
) { _, message ->
528-
Log.i("TAG", "KtChatMessages: message $message")
529-
if (message != null) {
530-
val imMessage = message.toIMMessage()
531-
KtChatIMMessage(
532-
imMessage = imMessage,
533-
message.sent,
534-
avatar = if (imMessage.fromId == me.uuid) {
535-
me.avatar
536-
} else {
537-
friend.avatar
538-
},
539-
name = if (imMessage.fromId == me.uuid) {
540-
me.nickname
541-
} else {
542-
friend.nickname
543-
},
544-
isUserMe = imMessage.fromId == me.uuid,
545-
timestamp = TimeUtils.millis2String(imMessage.timestamp),
546-
onAuthorClick = { name -> onAuthorClick(name) },
547-
resend = { resend(message) }
548-
)
549-
DayHeader(TimeUtils.millis2String(imMessage.timestamp))
550-
}
510+
pager?.let {
511+
val lazyPagingItems = it.flow.collectAsLazyPagingItems()
512+
var itemCount by remember { mutableStateOf(lazyPagingItems.itemCount) }
513+
val scope = rememberCoroutineScope()
514+
Box(modifier = modifier) {
515+
LazyColumn(
516+
reverseLayout = true,
517+
state = scrollState,
518+
modifier = Modifier
519+
.testTag(ConversationTestTag)
520+
.fillMaxWidth()
521+
.wrapContentHeight()
522+
) {
523+
itemsIndexed(
524+
items = lazyPagingItems,
525+
// The key is important so the Lazy list can remember your
526+
// scroll position when more items are fetched!
527+
key = { _, message -> message.id }
528+
) { _, message ->
529+
Log.i("TAG", "KtChatMessages: message $message")
530+
if (message != null) {
531+
val imMessage = message.toIMMessage()
532+
KtChatIMMessage(
533+
imMessage = imMessage,
534+
message.sent,
535+
avatar = if (imMessage.fromId == me.uuid) {
536+
me.avatar
537+
} else {
538+
friend.avatar
539+
},
540+
name = if (imMessage.fromId == me.uuid) {
541+
me.nickname
542+
} else {
543+
friend.nickname
544+
},
545+
isUserMe = imMessage.fromId == me.uuid,
546+
timestamp = TimeUtils.millis2String(imMessage.timestamp),
547+
onAuthorClick = { name -> onAuthorClick(name) },
548+
resend = { resend(message) }
549+
)
550+
DayHeader(TimeUtils.millis2String(imMessage.timestamp))
551+
}
551552

553+
}
552554
}
553-
}
554-
Log.i("TAG", "KtChatMessages: itemCount $itemCount, ${lazyPagingItems.itemCount} ")
555-
if (itemCount == lazyPagingItems.itemCount) {
556-
scope.launch {
557-
Log.i(
558-
"TAG",
559-
"KtChatMessages:firstVisibleItemIndex ${scrollState.firstVisibleItemIndex} "
560-
)
561-
if (scrollState.firstVisibleItemIndex != 0) {
562-
scrollState.animateScrollToItem(0)
555+
Log.i("TAG", "KtChatMessages: itemCount $itemCount, ${lazyPagingItems.itemCount} ")
556+
if (itemCount == lazyPagingItems.itemCount) {
557+
scope.launch {
558+
Log.i(
559+
"TAG",
560+
"KtChatMessages:firstVisibleItemIndex ${scrollState.firstVisibleItemIndex} "
561+
)
562+
if (scrollState.firstVisibleItemIndex != 0) {
563+
scrollState.animateScrollToItem(0)
564+
}
563565
}
564566
}
567+
itemCount = lazyPagingItems.itemCount
565568
}
566-
itemCount = lazyPagingItems.itemCount
567569
}
570+
568571
}
569572

570573
@Preview

AndroidJetpackComposeSample/IMCore/src/main/java/com/nxg/im/core/data/db/dao/MessageDao.kt

+2-5
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@ interface MessageDao {
1616
@Query("SELECT * from message WHERE id =:id AND from_id =:fromId AND to_id =:toId AND chat_type=:chatType")
1717
suspend fun queryMessage(id: Long, fromId: Long, toId: Long, chatType: Int): Message?
1818

19-
@Query("SELECT * from message WHERE (from_id =:fromId AND to_id =:toId OR from_id =:toId AND to_id =:fromId ) AND chat_type=:chatType")
20-
suspend fun loadMessages(fromId: Long, toId: Long, chatType: Int): List<Message>
21-
22-
@Query("SELECT * FROM message order by id desc ")
23-
fun pagingSource(): PagingSource<Int, Message>
19+
@Query("SELECT * FROM message WHERE ((from_id =:fromId AND to_id =:toId ) OR (from_id =:toId AND to_id =:fromId ) )AND chat_type=:chatType order by id desc ")
20+
fun pagingSource(fromId: Long, toId: Long, chatType: Int): PagingSource<Int, Message>
2421

2522
}

AndroidJetpackComposeSample/IMCore/src/main/java/com/nxg/im/core/module/chat/ChatServiceImpl.kt

+19-19
Original file line numberDiff line numberDiff line change
@@ -58,18 +58,7 @@ object ChatServiceImpl : ChatService, SimpleLogger {
5858

5959
private suspend fun doSendMessage(message: Message) {
6060
logger.debug { "message: $message" }
61-
//生成protobuf
62-
val body = message.msgContent.toByteArray()
63-
val imCoreMessage = IMCoreMessage.newBuilder().apply {
64-
version = 1
65-
cmd = "chat"
66-
subCmd = "text"
67-
type = 0
68-
logId = 0
69-
seqId = message.id
70-
bodyLen = body.size
71-
bodyData = com.google.protobuf.ByteString.copyFrom(body)
72-
}.build()
61+
7362
if (message.uuid == 0L) {
7463
//获取uuid
7564
val uuid = generateUid()
@@ -82,6 +71,18 @@ object ChatServiceImpl : ChatService, SimpleLogger {
8271
KtChatDatabase.getInstance(Utils.getApp()).messageDao()
8372
.updateMessage(message)
8473
}
74+
//生成protobuf
75+
val body = message.msgContent.toByteArray()
76+
val imCoreMessage = IMCoreMessage.newBuilder().apply {
77+
version = 1
78+
cmd = "chat"
79+
subCmd = "text"
80+
type = 0
81+
logId = message.id
82+
seqId = message.uuid
83+
bodyLen = body.size
84+
bodyData = com.google.protobuf.ByteString.copyFrom(body)
85+
}.build()
8586
//通过WebSocket发送
8687
val result = IMWebSocket.send(imCoreMessage.toByteArray().toByteString())
8788
logger.debug { "doSendMessage: result $result" }
@@ -119,8 +120,8 @@ object ChatServiceImpl : ChatService, SimpleLogger {
119120
cmd = "chat"
120121
subCmd = "text"
121122
type = 0
122-
logId = 0
123-
seqId = message.id
123+
logId = message.id
124+
seqId = message.uuid
124125
bodyLen = body.size
125126
bodyData = com.google.protobuf.ByteString.copyFrom(body)
126127
}.build()
@@ -280,14 +281,14 @@ object ChatServiceImpl : ChatService, SimpleLogger {
280281
"chat" -> {
281282
when (imCoreMessage.subCmd) {
282283
"text" -> {
283-
//acknowledge
284+
//acknowledge(发送方处理)
284285
if (imCoreMessage.type == 1) {
285286
logger.debug { "handleReceiveMessage cancel ${imCoreMessage.seqId} job and remove!" }
286287
//移除ACK队列中的超时任务
287288
ackMap[imCoreMessage.seqId]?.cancel()
288289
logger.debug { "handleReceiveMessage: ${imCoreMessage.seqId} " + ackMap[imCoreMessage.seqId] }
289290
ackMap.remove(imCoreMessage.seqId)
290-
//更新uuid和状态
291+
//更新状态
291292
KtChatDatabase.getInstance(Utils.getApp()).messageDao()
292293
.queryMessage(
293294
imCoreMessage.seqId,
@@ -302,12 +303,12 @@ object ChatServiceImpl : ChatService, SimpleLogger {
302303
.messageDao().updateMessage(it)
303304
}
304305
}
305-
//notify
306+
//notify(接收方处理)
306307
if (imCoreMessage.type == 2) {
307308
val currentTime = System.currentTimeMillis()
308309
val message = Message(
309310
0,
310-
0,
311+
uuid = imCoreMessage.seqId,
311312
fromId = imMessage.fromId,
312313
toId = imMessage.toId,
313314
chatType = imMessage.chatType,
@@ -318,7 +319,6 @@ object ChatServiceImpl : ChatService, SimpleLogger {
318319
)
319320
KtChatDatabase.getInstance(Utils.getApp()).messageDao()
320321
.insertMessage(message)
321-
322322
//单聊,如果没有会话,则创建
323323
if (imMessage.chatType == 0) {
324324
AuthServiceImpl.getLoginData()?.let {

0 commit comments

Comments
 (0)