Issue
I'm trying to implement an offline cache using Room instead of OkHttp Cache. The cache result of each request is only valid for short time like 30 mins.
Here is the flow:
- The app first load data from database
- If the data is available and not expired, display it to user. If not:
- Load data from API
- Refresh cache with new expiration time(or time stamp)
Solution
There is NO automated or an in-built way to handle the time expiration in Room Persistence Library(Room Database). One has to handle it manually.
One way to do that is create two columns in the table:
createdDate
lastUpDatedDate
Whenever there is an Insert or an Update operation, the lastUpDatedDate
column should be updated with the current timestamp.
The next time a Read
operation happens, limit it by the TTL
(defined in Android Client) and whenever there is Write
operation, update the TTL
.
This is one way of doing it. Other ways can include implementing threads(or Couroutines, if Kotlin is used in code base).
Answered By - Abhishek Dutt
Answer Checked By - Mary Flores (JavaFixing Volunteer)