Nurseyit Tursunkulov
Nurseyit Tursunkulov

Reputation: 9380

how to synchronize Room data with Cloud Firestore?

I want to be sure that I can save data offline. How to synchronize data in Room with Firestore? When something inserted to Room Firestore must be updated as well.

Upvotes: 3

Views: 2280

Answers (1)

crysxd
crysxd

Reputation: 3490

Firestore already has a persistence layer included, you don't need Room at all. You can enable the offline support like this:

val settings = FirebaseFirestoreSettings.Builder()
    .setPersistenceEnabled(true)
    .build()
db.firestoreSettings = settings

Using Firestore for persistance has many benefits over Room (besides the saved effort and potential bugs). If you e.g. load all restaurants in a city, then go offline and then run a query on e.g. the best restaurants the query will still work and use the cached data even when the query was never run while being online.

You can also configure the cache size Firestore uses to meet your needs. Documents are cached in a LRU manner, so the documents which were not used for the longest time get removed from the cache first once it is full.

A best practice is to always use snapshot listeners. If you start a query in offline mode and the device gets back online, Firestore will automatically run the query again with the server and return the updated result to your UI.

Check out the docs and this video about Firestore offline mode for more details.

Upvotes: 1

Related Questions