Anakhand
Anakhand

Reputation: 2998

How to listen to Firestore connectivity changes?

On my app, I want to listen to Firestore connectivity changes so that whenever the client goes offline, for example, I can show a message informing the user that data might not be up-to-date.

If I tell whether the client is offline or not by checking the fromCache metadata from query results, it might not be accurate: for example, when the client performs a write, even if it is online, it immediately applies the change to the local cache and sends this update to the corresponding listeners (with fromCache = true) while the update is actually being sent to the database—this is to reduce latency in the user experience.

Upvotes: 0

Views: 20

Answers (1)

Anakhand
Anakhand

Reputation: 2998

Inspired by this discussion on GitHub, one solution could be to have a dummy read-only document in your database (e.g. utils/dummy) and add a listener to it with includeMetadataChanges = true. When the client library notices it's gone offline, the listener will fire with a metadata change, namely fromCache will be true.

We can make the document read-only through security rules to ensure that our listener won't get other updates from the document changing, it will only get said metadata updates.

Example in Flutter/Dart:

db.doc("utils/dummy")
  .snapshots(includeMetadataChanges: true)
  .listen((snapshot) {
    if (snapshot.metadata.isFromCache) {
      // offline
    } else {
      // online
    }
  });

Upvotes: 1

Related Questions