Firestore 在离线模式下仍然需要与在线模式相同的时间

Firestore still take the same time in offline mode as compere to online

我在 android 中有一个片段,我从 firestore 中读取了一些数据,然后将其呈现在回收站视图中。问题是当设备离线时它仍然工作缓慢。我在文档中看到,数据持久性在 firestore 中默认处于启用状态。这是代码:

 firestore.collection(Constants.FireCollections.USERS)
            .document(FirebaseAuthRepository().getCurrentUserId())
            .collection("categories")
            .get().addOnSuccessListener {
                for (c in it) {
                    defaultCategories.add(c.toObject(Category::class.java))
                }
                Log.i(TAG, "Category: $defaultCategories")
                binding.recyclerViewIcons.adapter = CategoryIconAdapter(defaultCategories, this@OutflowTransactionFragment)
            }

我需要它至少比从 firestore 在线模式读取更快地工作。而且我希望在线模式也从缓存数据中本地获取数据而不是在线获取数据以提高速度,因此当设备在线时它只更新捕获的数据。

总的来说我想要的速度。

感谢阅读本文。

答案很简单,只需将调用从服务器重定向到缓存即可。

如果您在应用中使用 Firestore,那么您可能会注意到在离线模式下从 Firestore 获取数据时出现微小的延迟。这是因为 Firebase Firestore 在加载失败时首先在服务器中检查数据,然后再次从缓存中获取数据。

问题和微小的延迟是因为两次调用。因此,为了克服延迟,我们需要从缓存中获取数据,这非常简单,只需将 Source.CACHE 传递给 get() 方法即可。默认调用始终来自服务器,因此我们需要添加缓存:

val source = Source.CACHE
firestore.collection(Constants.FireCollections.USERS)
   .document(FirebaseAuthRepository().getCurrentUserId())
   .collection("categories")
   .get(source).addOnSuccessListener {
       for (c in it) {
                        
       defaultCategories.add(c.toObject(Category::class.java))
      }
   Log.i(TAG, "Category: $defaultCategories")
   binding.recyclerViewIcons.adapter = CategoryIconAdapter(defaultCategories, this@OutflowTransactionFragment)
 }

希望这对您有所帮助,如果需要更多说明,请在评论部分告诉我。