简体   繁体   English

如何避免对使用带有 firestore 的 snapshotListener 删除的消息调用 onEvent(QuerySnapshot snapshots, FirestoreException error)?

[英]How to avoid call onEvent(QuerySnapshot snapshots, FirestoreException error) for message deleted using the snapshotListener with firestore?

I am using Firestore in Java with the method:我在 Java 中使用 Firestore 的方法是:

 firestore.collection("myCollection").addSnapshotListener(listener);

My listener is:我的听众是:

 EventListener<QuerySnapshot> listener = new EventListener<QuerySnapshot>() {
        WriteBatch wb = firestore.batch();
        @Override
        public void onEvent(QuerySnapshot snapshots, FirestoreException error) {
           snapshots.forEach(doc -> {
                // do something with the doc and then delete it
                ...
                wb.delete(doc.getReference()
        }
        wb.commit(); 
}

The problem is that when I delete the documents I call again the onEvent method.问题是,当我删除文档时,我再次调用onEvent方法。 There is a way to avoid it?有办法避免吗?

There is a way to avoid it?有办法避免吗?

Sure there is.当然有。 What you are doing is adding a real-time listener which is triggered every time you make a change at your myCollection location.您正在做的是添加一个实时侦听器,每次在myCollection位置进行更改时都会触发该侦听器。 Doesn't matter if it's a delete, write or even an update operation, the onEvent() method fires.无论是删除、写入还是更新操作, onEvent()方法都会触发。 To avoid this, you should get the data only once by using Query's get() method.为避免这种情况,您应该使用 Query 的get()方法只获取一次数据。 This is the correspondent addListenerForSingleValueEvent() method from Firebase Realtime Database.这是来自 Firebase 实时数据库的相应addListenerForSingleValueEvent()方法。

Edit:编辑:

According to your comment:根据您的评论:

There is a way to use the listener and having the onEvent fired only with create (or create and update) operations?有一种方法可以使用侦听器并仅通过创建(或创建和更新)操作触发 onEvent?

Yes, it is, you can view the changes between snapshots using a switch statement, as explained the official documentation regarding changes between snapshots .是的,您可以使用 switch 语句查看快照之间的更改,如有关快照之间更改的官方文档所述。

It is often useful to see the actual changes to query results between query snapshots, instead of simply using the entire query snapshot.查看查询快照之间查询结果的实际更改通常很有用,而不是简单地使用整个查询快照。 For example, you may want to maintain a cache as individual documents are added, removed, and modified.例如,您可能希望在添加、删除和修改单个文档时维护缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM