我正在尝试实时阅读消息,问题是当人员A向人员B发送消息时,人员B实时侦听器调用了添加事件,这完全可以理解,但是为什么还删除了事件叫吗?
fun readMessagesRealTimeListener(documentID: String, date: Date, senderUser: ChatUser, reciverUser: ChatUser): LiveData<List<ChatMessage>> {
if (mutableChatMessageList == null) {
mutableChatMessageList = MutableLiveData()
val chatMessageList = ArrayList<ChatMessage>()
db = FirebaseFirestore.getInstance()
readMessageListener = db.collection(Constants.CONVERSATION)
.document(documentID)
.collection("0")
.orderBy("data", Query.Direction.DESCENDING)
.limit(5)
.addSnapshotListener(EventListener<QuerySnapshot> { querySnapshot, e ->
if (e != null) {
Log.d(TAG, "error in real time listerner: " + e.code);
}
val source = if (querySnapshot != null && querySnapshot.metadata.hasPendingWrites())
"Local"
else
"Server"
Log.d(TAG, "source of $source")
chatMessageList.clear()
if (!querySnapshot?.isEmpty!!) {
for (changedSnapshot in querySnapshot.documentChanges) {
when (changedSnapshot.type) {
DocumentChange.Type.ADDED -> Log.d(TAG, "New message: " + changedSnapshot.getDocument().getData())
DocumentChange.Type.MODIFIED -> Log.d(TAG, "Modified message: " + changedSnapshot.getDocument().getData())
DocumentChange.Type.REMOVED -> Log.d(TAG, "Removed message: " + changedSnapshot.getDocument().getData())//this log also called when new document added in firestore but why?
}
var chatMessage = changedSnapshot.document.toObject(ChatMessage::class.java)
Log.d(TAG, "message " + chatMessage.message)
chatMessageList.add(chatMessage)
}
mutableChatMessageList?.value = chatMessageList
} else {
Log.d(TAG, "no message found in real time")
mutableChatMessageList?.setValue(null)
}
})
}
return mutableChatMessageList!!
}
答案 0 :(得分:0)
一个快速的猜测是您的收藏集中有5条以上的消息。在这种情况下,此侦听器仅显示最新的5条消息:
readMessageListener = db.collection(Constants.CONVERSATION)
.document(documentID)
.collection("0")
.orderBy("data", Query.Direction.DESCENDING)
.limit(5)
因此,现在添加新消息时,该新消息将成为最新消息。并且先前的第一条消息已从QuerySnapshot
中删除。
最简单的方法是查看我们是否迅速草拟邮件。假设您从以下5点开始:
1
2
3
4
5
因此,这5条消息将调用您的听众。现在,我们添加了一条新消息6
。此新消息将被添加到QuerySnapshot
中。但这将导致它收到6条消息,而您只要求5条消息。因此,您为ADDED
得到了6
,为`1得到了REMOVED
。
1 REMOVED
2
3
4
5
6 ADDED
最后得到:
2
3
4
5
6