3

I am using Firebase Firestore and I'm facing a problem with the read operation: I use an onCompleteListener, and inside there, I call different callbacks if the operation was successfull or not. The problem is, if there is a network issue, the onCompleteListener is called, but task.isSuccessfull returns true!! So I get an empty result which I can't distinguish from a REAL empty result. Is there any way to distinguish a network issue from an empty read?

Thank you very much! My function is just below:

dataBase.collection(COLLECTION) .whereEqualTo(FIELD, searched) .get() .addOnCompleteListener { task: Task<QuerySnapshot> -> if (task.isSuccessful) { listenerSuccess(task.result) } else { listenerError() } } 

1 Answer 1

7

If you're offline, the client will first try to connect. Once it figures out that it can't connect, it will try to complete the get() based on the data in the local database. That's a valid action on Firestore, so that's why the task is completed successfully.

You can detect if the results came from the local cache vs which came straight from the server, by checking the metadata: querySnapshot.getMetadata().isFromCache(). From the docs:

true if the snapshot was created from cached data rather than guaranteed up-to-date server data. If your listener has opted into metadata updates (via MetadataChanges.INCLUDE) you will receive another snapshot with isFomCache() equal to false once the client has received up-to-date data from the backend.

Sign up to request clarification or add additional context in comments.

2 Comments

I will try it tonight, but I think this may solve my problem. Thank you!
I have been able to fix it thanks to better undestanding Firestore behaviour without connection. It worked like a charm!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.