Search code examples
androidfirebaseandroid-recyclerviewlistenergoogle-cloud-firestore

Differentate between first time querysnapshot and change listener in firestore


I'm following the documentation of firestore here and trying to attach a snapshot listener on a collection for getting realtime updates.

I'm having trouble trying to differentiate between whether a response from the Snapshot event listener is a first time response (in which case all the documents in the collection will be returned) or a change event response in which case I want to add the check to identify what change happened. This footnote in the same documentation which goes as :

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

doesn't mention how to identify a first query snapshot with that of subsequent ones.

Only related question I can find on SO is this one but it wouldn't help in my case.

Any help is really appreciated since I've run out of directions to go to.

Thanks.


Solution

  • Take a careful look at the code in the docs you referenced. It's checking the Type of each DocumentChange object in the QuerySnapshot object:

    for (DocumentChange dc : snapshots.getDocumentChanges()) {
        switch (dc.getType()) {
            case ADDED:
                Log.d(TAG, "New city: " + dc.getDocument().getData());
                break;
            case MODIFIED:
                Log.d(TAG, "Modified city: " + dc.getDocument().getData());
                break;
            case REMOVED:
                Log.d(TAG, "Removed city: " + dc.getDocument().getData());
                break;
        }
    }
    

    This goes along with the text you cited:

    The first query snapshot contains added events for all existing documents that match the query.

    You can tell if you've seen a document for the first time because it's an ADDED type of change. MODIFIED and REMOVED type changes are only issued for documents you've seen previously for this listener.