Firebase Firestore how to identify an offline read

2019-07-25 15:15发布

问题:

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:

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.