DEV Community

Rahul Chowdhury 🕶
Rahul Chowdhury 🕶

Posted on

Day 7: Hey look, I got a list of elephants

Hi there, it's day 7 of my job hunt journey.

Yesterday's work

Implementing Jetpack's Navigation component was a breeze. It's great to see how far Android app development has come.

The core Android team has done a fabulous job in making common use cases easy to implement so that developers can focus more on the business logic of their apps.

Apart from that, I did a little bit of refactoring here and there.

Today?

I started working on fetching a list of elephants from the Elephant API.

When it came to caching a list of elephants, I had 2 options:

  • Solution A: Serialise and store a list of elephants in the local DB, separate from the previous Elephant model.
  • Solution B: Store all elephant objects in the list as individual records, as they were stored in the elephant profile screen.

There were pros and cons of both approaches but ultimately I decided to go with solution B.

Pros and cons

  • Solution A:
    • Pros: It's easy to implement and check for last update time to determine whether the list needs to be re-fetched.
    • Cons: Not flexible. Have to maintain similar data in 2 places. Can result in data inconsistency. For example, let's say the list of elephants is refreshed in the main screen and the list data in DB is updated with the latest copy. However, the profile screen still fetches cached data from individual elephant entities which might not have the latest copy because their cache time hasn't yet expired.
  • Solution B:
    • Pros: Data is consistent because elephant details on both the list screen and the profile screen are fetched from the same DB row. Thus, if one screen updates the data, the other screen automatically gets the latest update.
    • Cons: Caching logic is not straightforward like solution A because there is more than 1 item to check staleness of data.

This is the logic that I applied to determine the staleness of the list:

private suspend fun refreshElephantListIfNeeded() {
    val staleTime = System.currentTimeMillis() - Constants.Time.FRESHNESS_PERIOD_IN_MILLIS
    val staleElephants = elephantDao.loadStaleElephants(staleTime)

    if (staleElephants.isNotEmpty()) {
        val elephantListResponse = elephantApiService.fetchElephants()
        val normalisedElephants = elephantListResponse
            .filter { it.name != null }
            .map { it.toElephant() }

        elephantDao.saveMultiple(normalisedElephants)
    }
}

You can find the updated project here: https://github.com/rahulchowdhury/elly

I'm also exploring my options to test repositories for my app. Let's see what I find.

Top comments (0)