Reputation: 399
I have a fragment in android where I read some data from firestore and than present it in the recycler view. the thing is it still working slow the same when device is go offline. I see in documentation that data persistence is on by default in firestore. here is the code:
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)
}
I need this to work fast at least fast than reading from firestore online mode. and I want the online mode also to fetch the data locally from cached data instead of online for speed so when the device comes online it just update the catched data.
overall the desired result I want the speed.
Thanks for reading this.
Upvotes: 3
Views: 311
Reputation: 399
The answer is very simple just by redirecting the call from the server to cache will do the magic.
If you are using Firestore in your app then you may notice a tiny delay in when you are getting data from Firestore in offline mode. and this because due to Firebase Firestore checks first in the server the data when it fails to load then again it takes the data from cache.
The problem and the tiny delay is because of two calls. so to overcome the delay we need get data from cache and this very simple by passing Source.CACHE
to get()
method. The default call is always from server so we need to add cache:
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)
}
Hope this help, let me know in the comment section if need for more clearification.
Upvotes: 2