Digvijay
Digvijay

Reputation: 3271

How to use room database as a cache

I am making an android app using MVVM architecture. I want to fetch data from an API and insert it into room database and then fetch it from the room in my app. I don't know if it is a better way to implement database cache functionality. If there is some other or better way to do so please let me know.

Upvotes: 2

Views: 8187

Answers (1)

a_local_nobody
a_local_nobody

Reputation: 8191

your question explains exactly how you would use Room:

  1. fetch data from an api
  2. insert it into room database
  3. fetch it from room in my app

Room allows you to store your data locally and retrieve this data with various different threads, making use of something like Rxjava, it also allows you to observe onto any changes with LiveData, Room is definitely a decent option to consider for caching

BUT

Using Room is ONE of SEVERAL different implementations of caching, consider posting code or a specific scenario for better answers. Happy coding.

Edit:

A common approach to using Room (or any caching) would be to either load initial data from the database, display this to the user, perform an api call, update the cache and display this updated data from the api

OR

If the user does not have an internet connection, simply use what he has available in the cache as data. Again, all of this depends on your specific scenario.

Upvotes: 10

Related Questions