Paging 3 - Use cached data only if no internet, else do API requests

Viewed 333

I tried to use RemoteMediator to fetch data from an API and cache the response, and generally it works great.

I need something a bit different than the normal behaviour. by default it seems it automatically fetches cached data first (from room) and only when it reaches the end of the list, it performs another request. To make sure that you get fresh data, I saw in the docs that I have to clear the cached data every time the user makes a new search (in order to invalidate the flow and update the RecyclerView's list).

What I want to do is to always perform an API request (if the user have internet), and use the cached data only if he doesn't have an internet connection (the cached data needs to be persisted, so I can't delete it because I need to use it as a foreign key with other entities in the database).

Any suggestions are appreciated. Thanks!

1 Answers

All the items loaded and presented by Paging are entirely driven by the PagingSource. In this scenario you can just hold off on deleting cached data until your network request succeeds and only then, delete + write the new data in.

E.g.,

class MyRemoteMediator(...) : RemoteMediator<Int, ...>() {
    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, RedditPost>
    ): MediatorResult {
        try {
            val items = networkApi.fetchItems(..)

            db.withTransaction {
                if (loadType == REFRESH) {
                    // Clear cache
                }

                // Insert items into cache
                // Now call .invalidate()
            }

            return MediatorResult.Success(...)
        } catch (e: IOException) {
            return MediatorResult.Error(e)
        }
    }
}
Related