2

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.

Didier Corronel
  • 325
  • 3
  • 11

2 Answers2

5
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.

RmK
  • 1,408
  • 15
  • 28
  • 1
    Thanks for this bro, You are the real hero bro :), you must be awarded Nobel prize. – Raj Jan 07 '19 at 12:54
  • 1
    @Raj No, no Nobel prize. This solution is very very superficial, all it is doing is ignoring the first fetch of data using an (if...else) statement. The only solution to the OP's question is to wait for the firestore team to give us an API which can make the initial snapshot optional. – varun Oct 22 '20 at 07:10
  • Further, the AtomicBoolean you use is as good as a default volatile boolean value, because you are not using any special atomic methods of the class, so this code does not prevent race conditions during any parallel executions! Refer: https://stackoverflow.com/a/39352047/6086782 – varun Oct 22 '20 at 07:14
4

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".

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807