Check if a Firestore Document exist locally

Viewed 412

What is the best way to check if a Document exists locally?

Should you always use disableNetwork() as the documentation says ?

The problem with this method is that you have to reactivate the network each time using enableNetwork() otherwise the next calls will all be made locally.

Isn't there a more effective method?

1 Answers

Check if a Firestore Document exists locally

Starting with the 16.0.0 SDK version update, we can check if a Firestore document exists locally with the help of the DocumentReference.get(Source source) method or Query.get(Source source) method if we are interested to check if the documents that come as a result of a query actually exist.

By default, get() attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. This behavior can be altered via the Source parameter.

So we can now pass as an argument to the DocumentReference or to the Query the source so we can force the retrieval of data from the cache only.

So you should use something like this:

val root = FirebaseFirestore.instance
val docIdRef = root.collection("CollectionName").document(docId)
docIdRef.get(Source.CACHE).addOnSuccessListener(/* ... */)

In this case, we force the data to be retrieved from the cache only. If you want to get the data from the server only, you should pass as an argument to the get() method, Source.SERVER. More informations here.

Related