Home > OS >  Firebase Stream - Knowing when initial fetch complete?
Firebase Stream - Knowing when initial fetch complete?

Time:04-19

I use a Firebase Realtime Database StreamSubscription to listen to events including onChildAdded and onChildChanged.

For example this will fetch all existing entries at dbRef and any future additions while the stream is active.

dbRef.onChildAdded.listen((event) async {
      String? key = event.snapshot.key;
      Map value = event.snapshot.value as Map;
      // Do stuff with object...
    });

However, as onChildAdded fetches ALL data and then subsequent additions, I don't know when the initial/existing data is finished fetching.

I could use dbRef.once() which would fetch the initial/existing data and I would know when that is complete, allowing me to present a loading UI. However, using onChildAdded after this would leave me fetching data twice.

How can I fetch the initial/existing data, know when that is done, so that a loading UI can be displayed appropriately and then listen to future additions?

CodePudding user response:

firebaser here

If you listen to both child and value events in the Realtime Database, the value event for an update will only fire after all child events for that same have fired.

Knowing this, a common trick is to listen to both onChild... and onValue events (or the once future). You can then build/update the state in the child handlers, and commit the new state in the value handler.

The SDK automatically deduplicates listeners on the same query/reference, so having multiple listeners on the same query/ref will only read the data from the server once.

  • Related