Search code examples
c#firebaseunity-game-enginegoogle-cloud-firestorelistener

Firestore "ListenerRegistration" being called when listener is created, should be?


I'm using Unity with Firebase SDK, using Auth and Firestore utilities from Firebase.

I can make all kinds of operations to my Firestore Database from my client, so now I'm trying to implement some client-side hooks, so when something in Firestore changes, the client will perform an action.

The way that I'm building those listeners is inspired on Firebase Documentation and this is an example of a method that I use to set a listener to a Firestore collection if something changes:

//db == FirebaseFirestore.DefaultInstance;

public ListenerRegistration SetListenerToAllCollectionDocuments(string collectionID, Query query = null, Action OnSomeDocumentChange = null)
{
    try
    {
        Query colRef = query ?? db.Collection(collectionID);

        ListenerRegistration listener = colRef.Listen(colQuerySnapshot =>
        {
            Debug.Log("Listen changes on collection:" + collectionID);
            OnSomeDocumentChange();                
        });
        return listener;
    }
    catch (Exception e)
    {
        Debug.Log(e);
    }
    return null;
}

Then I can call it like:

ListenerRegistration listener = Database.SetListenerToAllCollectionDocuments("users", null, () => { Debug.Log("Something Change"); });

to have the listener reference if I want to disable it.

So far so good, now the problem: This listener is correctly called when something in the database changes, but is ALSO called when I call the method SetListenerToAllCollectionDocuments(); for first time, when setting the listeners.

Should be this the expected behaviour?

On my head this should only be called when something on firestore changes, not when I'm creating the listener. What I'm doing wrong? Thanks.


Solution

  • It is expected that a listener is called with all existing data in the collection/query when you attach it.

    If you want to get only new data/updates, you'll need to ensure this in your application code. The common way is to add a lastUpdated timestamp in each document, and then query for items where lastUpdated is after now.