Search code examples
androidandroid-room

Is there any way to set TTL (expiration) for Room record in Android?


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:

  1. The app first load data from database
  2. If the data is available and not expired, display it to user. If not:
  3. Load data from API
  4. 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:

    1. createdDate
    2. 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).