检查本地是否存在文档
的最佳方法是什么?
您是否应该始终使用 disableNetwork()
作为 documentation says ?
此方法的问题在于,每次使用 enableNetwork()
都必须重新激活网络,否则接下来的调用都将在本地进行。
有没有更有效的方法?
最佳答案
Check if a Firestore Document exists locally
从16.0.0 SDK版本更新开始,我们可以借助DocumentReference.get(Source source)检查本地是否存在Firestore文档。方法或Query.get(Source source)方法,如果我们有兴趣检查作为查询结果的文档是否确实存在。
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.
因此,我们现在可以将源作为参数传递给 DocumentReference 或 Query,这样我们就可以强制仅从缓存中检索数据。
所以你应该使用这样的东西:
val root = FirebaseFirestore.instance
val docIdRef = root.collection("CollectionName").document(docId)
docIdRef.get(Source.CACHE).addOnSuccessListener(/* ... */)
在这种情况下,我们强制仅从缓存中检索数据。如果您只想从服务器获取数据,则应将 Source.SERVER
作为参数传递给 get()
方法。更多信息here .
关于android - 检查本地是否存在 Firestore 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62404536/