Listen For MetaData Changes in Firebase Firestore database

自作多情 提交于 2020-01-25 07:27:31

问题


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 ");

                                }
                            }
                        }
                    }
                });

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?


回答1:


When passing a MetadataChanges to the Query's addSnapshotListener(MetadataChanges metadataChanges, EventListener listener) method:

Indicates whether metadata-only changes (i.e. only Query.getMetadata() changed) should trigger snapshot events.

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

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


来源:https://stackoverflow.com/questions/54253438/listen-for-metadata-changes-in-firebase-firestore-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!