Skip to content
Commitwise
Menu

How would you build an offline-first paginated list on Android?

AndroidSenior

In shortMake Room the single source of truth. The UI pages through Room's PagingSource, a RemoteMediator loads network pages into the database (with a remote-keys table for cursors and transactional refreshes), and the Pager flow is cached in the ViewModel.

Model answer

Architecture:

  • Room is the source of truth. The DAO returns a PagingSource<Int, OrderEntity>, which Room invalidates automatically when the table changes.
  • A RemoteMediator loads pages from the API when Paging reaches the end of cached data (APPEND) or on refresh (REFRESH). It writes the page and the next cursor (in a remote-keys table) inside one transaction; on refresh it clears old rows in the same transaction to avoid an empty flash.
  • Pager(config, remoteMediator, pagingSourceFactory = { dao.pagingSource() }), with .cachedIn(viewModelScope) so configuration changes reuse loaded pages.
  • initialize() returns SKIP_INITIAL_REFRESH when the cache is fresh enough, so opening the screen doesn’t always hit the network.

UI: collectAsLazyPagingItems(), stable keys with itemKey { it.id }, and load states: loadState.mediator?.refresh for network refresh errors shown over cached content, append errors as a retry row at the end.

Offline behavior: without network, the list shows cached rows; mediator errors don’t clear anything. Pull-to-refresh calls refresh(). Local edits go to Room first and sync through a queue (for example WorkManager), so they appear immediately.

What they're looking for

Room as the source of truth, RemoteMediator responsibilities, remote keys, transactions, load states for UI, cachedIn, and handling refresh, errors and staleness.

Common mistakes

  • Reading from the network PagingSource and caching separately.
  • Clearing the table and inserting in separate transactions.
  • Creating the Pager in a composable.

More android questions

Esc

Type to search the whole site.