侦听Firebase Firestore数据库中的元数据更改 [英] Listen For MetaData Changes in Firebase Firestore database
问题描述
我正在使用Firestore数据库创建聊天模块.以下是我的侦听器代码,用于侦听以下内容中的新消息:
I am creating a chat module using Firestore database. Following is my listener code that listen for new messages in:
mDb.collection("Users_Collection").document(mAuth.getUid()).collection("Recipients")
.document(psychichObj.getUid()).collection("Messages").orderBy("time").limit(30)
.addSnapshotListener(MetadataChanges.INCLUDE, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if (e==null){
for (DocumentChange dc:queryDocumentSnapshots.getDocumentChanges()){
switch (dc.getType()){
case ADDED:
Log.d("chatevents", "onEvent:Added ");
messgaesDataClass msg = dc.getDocument().toObject(messgaesDataClass.class);
messages.add(msg);
chatAdapter.notifyDataSetChanged();
messagesRecycler.smoothScrollToPosition(messages.size());
break;
case REMOVED:
Log.d("chatevents", "onEvent:Removed ");
case MODIFIED:
Log.d("chatevents", "onEvent:Modiefied ");
}
}
}
}
});
当我发送一条消息时,我想知道如何侦听位于本地缓存中或其元数据处于待处理状态且尚未发送到服务器的msg对象?
When I send a message than I want to know how can I listen for a msg object that is in local cache or whose metadata is in pending state and not sent to the server yet?
推荐答案
When passing a MetadataChanges to the Query's addSnapshotListener(MetadataChanges metadataChanges, EventListener listener) method:
指示仅元数据更改(即仅Query.getMetadata()已更改)是否应触发快照事件.
Indicates whether metadata-only changes (i.e. only Query.getMetadata() changed) should trigger snapshot events.
从本质上讲,这意味着每次元数据更改时,都会触发侦听器.因此,在进行暂挂操作的情况下,变量 pending
的值将被更改.
Which basically means that every time the metadata changes, the listener is triggered. So in case of pending operations, the value of the variable pending
will be changed.
我想知道如何监听本地缓存中的味精对象
I want to know how can i listen for a msg object that is in local cache
在这种情况下,您应该考虑使用SnapshotMetadata的
In this case, you should consider using SnapshotMetadata's isFromCache() method:
Log.d(TAG, "isFromCache: " + documentSnapshot.getMetadata().isFromCache());
当我在线时,它会打印:
When I'm online it prints:
isFromCache: false
当我离线时,它会打印:
When I'm offline, it prints:
isFromCache: true
这篇关于侦听Firebase Firestore数据库中的元数据更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!