Firebase Firestore如何识别脱机读取 [英] Firebase Firestore how to identify an offline read

查看:69
本文介绍了Firebase Firestore如何识别脱机读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase Firestore,并且遇到读取操作问题: 我使用onCompleteListener,在其中,如果操作成功或失败,我将调用不同的回调. 问题是,如果存在网络问题,则会调用onCompleteListener,但是task.isSuccessfull返回true!所以我得到一个空的结果,我无法与一个真正的空结果区分开.有什么方法可以将网络问题与空读取区分开来吗?

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()
            }
        }

推荐答案

如果您处于脱机状态,则客户端将首先尝试连接.一旦确定无法连接,它将尝试基于本地数据库中的数据完成get().这是对Firestore的有效操作,所以这就是任务成功完成的原因.

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(如果快照是从缓存的数据而不是有保证的最新服务器数据创建的).如果您的监听器(通过MetadataChanges.INCLUDE)选择了元数据更新,则一旦客户端从后端接收了最新数据,您将收到另一个isFomCache()等于false的快照.

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.

这篇关于Firebase Firestore如何识别脱机读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆