onReceiveNewMessage method

void onReceiveNewMessage(
  1. V2TimMessage newMessage
)

Callback for receiving new message function(V2TimMessage)

Implementation

void onReceiveNewMessage(V2TimMessage newMessage) {
  String conversationID = TencentCloudChatUtils.checkString(newMessage.groupID) ?? TencentCloudChatUtils.checkString(newMessage.userID) ?? "";
  List<V2TimMessage> messageList = getMessageList(key: conversationID);

  // Check if the message list already contains the new message.
  bool messageExists = messageList.any((message) => message.msgID == newMessage.msgID);

  if (!messageExists) {
    // If the new message is consecutive, add it to the list.
    if (!getMessageListStatus(userID: newMessage.userID, groupID: newMessage.groupID).haveMoreLatestData) {
      messageList.insert(0, newMessage);

      // Ensure the message list doesn't exceed the maximum message count.
      if (messageList.length > maxMessageCount) {
        messageList = messageList.take(maxMessageCount).toList();
        final key = TencentCloudChatUtils.checkString(newMessage.groupID) ?? TencentCloudChatUtils.checkString(newMessage.userID) ?? "";
        _messageListStatusMap[key]!.haveMorePreviousData = true;
      }

      // Update the message list in the data store.
      updateMessageList(userID: newMessage.userID, groupID: newMessage.groupID, messageList: messageList);
    }
  }
}