Disable the first query snapshot when adding a sna

2020-03-31 07:47发布

Firestore realtime updates documentation here

Here is the comment you can find in the documentation.

Important: The first query snapshot contains added events for all existing documents that match the query. This is because you're getting a set of changes that bring your query snapshot current with the initial state of the query. This allows you, for instance, to directly populate your UI from the changes you receive in the first query snapshot, without needing to add special logic for handling the initial state.

I understand how it can be usefull but in some case it just bother me and I'd like to know if there are any way to prevent that first query snapshot from trigerring the listener.

2条回答
男人必须洒脱
2楼-- · 2020-03-31 08:19
AtomicBoolean isFirstListener = new AtomicBoolean(true);

commentListener = getLectureCommentsCollecReference(courseId, lectureId)
                .addSnapshotListener((queryDocumentSnapshots, e) -> {
                    if (isFirstListener.get()) {
                        isFirstListener.set(false);
                        //TODO Handle the entire list. 
                        return;
                    }
                    for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
                        switch (dc.getType()) {
                            case ADDED:
                                sendCommentAddedEvent(DataParser.parseComment(dc));
                            case MODIFIED:
                                sendCommentUpdatedEvent(DataParser.parseComment(dc));
                                break;
                        }
                    }
                });

This is one way of doing it. I use this inside a comment feature for listening to new comment Added as well as if comments are modified.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-03-31 08:36

There is no way to suppress getting the initial data.

Depending on the use-case, you may want to attach your listener to a subset of the data. E.g. if you have an append-only scenario (such as chat), you can start listening for data that was modified after "now".

查看更多
登录 后发表回答