skip to content

In Paging 3, how does a RemoteMediator fill a Room cache for an offline wine catalogue, and how do newly fetched wines reach the list?

level: seniorimportance: should knowfreq 38%

answer

  1. the database is the source of truth
  2. called at the edges of the cache
  3. load(LoadType, PagingState) returns MediatorResult
  4. the write invalidates the PagingSource
  5. @ExperimentalPagingApi opt-in

basics

~20 s

The Pager reads only from Room's PagingSource; when it reaches an end or a refresh is requested, Paging calls RemoteMediator.load(), which fetches a page and writes it to the database. That write invalidates the PagingSource, so a new generation shows the wines.

solid answer

~40 s

With a `RemoteMediator`, the database is the single source of truth: the `Pager`'s `pagingSourceFactory` returns the DAO's `PagingSource`, and the mediator never hands items to the UI. Paging calls `load(loadType, state)` for `REFRESH` (on stream start unless `initialize()` returns `SKIP_INITIAL_REFRESH`, and on a UI `refresh()`), and for `APPEND` or `PREPEND` when the local source returns a page whose `nextKey` or `prevKey` is `null`. The mediator fetches the next page, stores it and its remote key in one transaction, and returns `MediatorResult.Success(endOfPaginationReached)` or `MediatorResult.Error`. Room invalidates its `PagingSource` on that write, so Paging builds a new one that reloads around the user. `RemoteMediator` and the `Pager` constructor that takes it are `@ExperimentalPagingApi`, so both need an opt-in.

code

kotlin · 34 lines
kotlin
@OptIn(ExperimentalPagingApi::class)
class WineRemoteMediator(
    private val api: WineApi,
    private val cache: WineCache, // app code over Room: wines table + remote keys
) : RemoteMediator<Int, Wine>() {

    override suspend fun initialize(): InitializeAction =
        if (cache.isFresh()) InitializeAction.SKIP_INITIAL_REFRESH
        else InitializeAction.LAUNCH_INITIAL_REFRESH

    override suspend fun load(loadType: LoadType, state: PagingState<Int, Wine>): MediatorResult {
        val page = when (loadType) {
            LoadType.REFRESH -> 1
            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
            LoadType.APPEND -> cache.nextPage()
                ?: return MediatorResult.Success(endOfPaginationReached = true)
        }
        return try {
            val wines = api.wines(page = page, perPage = 10)
            // one transaction: clear on REFRESH, insert wines, store the next page key
            cache.store(wines, nextPage = page + 1, clear = loadType == LoadType.REFRESH)
            MediatorResult.Success(endOfPaginationReached = wines.isEmpty())
        } catch (e: IOException) {
            MediatorResult.Error(e)
        }
    }
}

@OptIn(ExperimentalPagingApi::class)
val pager = Pager(
    config = PagingConfig(pageSize = 10),
    remoteMediator = WineRemoteMediator(api, cache),
    pagingSourceFactory = { wineDao.pagingSource() },
)

go deeper

for a junior

Recall that RemoteMediator loads from the network into the database and the list reads only from the database's PagingSource.

for a middle

Explain when Paging calls load() for REFRESH, APPEND and PREPEND, what MediatorResult.Success and Error mean, and what initialize() controls.

for a senior

Trace a page that is stored but never shown back to a missing invalidation, a wrong table or an end-of-pagination flag, and keep rows and remote keys in one transaction.

for a principal

Weigh the experimental opt-in, the extra schema and the testing cost of a mediator against the offline experience it buys, per feed rather than app-wide.

## The shape of the pipeline Paging from a network into a local cache uses **`RemoteMediator<Key, Value>`** next to an ordinary `PagingSource`: - The **`PagingSource`** reads from the database, typically the one a Room DAO returns. It is the only thing that feeds `PagingData`. - The **`RemoteMediator`** is a signal handler. Paging calls it when the cached data runs out or a refresh is requested, and its job is to fetch from the network and **write to the database**. - The **database write** is what makes new data visible: it invalidates the `PagingSource`, the `Pager` creates a new one, and the new generation includes the new rows. Because the UI only ever shows what is in the database, a winery catalogue keeps working offline: the cached wines page in from Room whether or not the network answers. ## When Paging calls load() `suspend fun load(loadType: LoadType, state: PagingState<Key, Value>): MediatorResult` is called for: 1. **`REFRESH`** when the stream starts and `initialize()` returns `InitializeAction.LAUNCH_INITIAL_REFRESH` (the default), or when the UI calls `refresh()`. A refresh normally clears the cached rows and loads the first page. 2. **`APPEND`** when the `PagingSource` returns a page with `nextKey == null`, meaning the database has nothing further. 3. **`PREPEND`** when it returns a page with `prevKey == null`. A feed that always refreshes from the top returns `MediatorResult.Success(endOfPaginationReached = true)` straight away for this. `state` is a snapshot of the pages in memory, so `state.lastItemOrNull()` can supply the key for an item-keyed API. When the API pages by token or page number that is not stored on each item, keep a **remote keys** table and read the next key from it. The `load()` KDoc adds three guarantees: - calls are not concurrent unless `Pager.flow` has several collectors, one more reason to `cachedIn`; - a `REFRESH` has priority: Paging may cancel an in-flight `APPEND` or `PREPEND` and run the `REFRESH` first; - with `LAUNCH_INITIAL_REFRESH`, `APPEND` and `PREPEND` wait until that `REFRESH` succeeds. ## What load() returns | Result | Meaning | |---|---| | `MediatorResult.Success(endOfPaginationReached = false)` | stored a page, more may follow | | `MediatorResult.Success(endOfPaginationReached = true)` | nothing more in this direction | | `MediatorResult.Error(throwable)` | recoverable failure, reported as `LoadState.Error` and retryable with `retry()` | These results show up in `CombinedLoadStates.mediator`, while `CombinedLoadStates.source` reports the database loads. ## Remote keys The key the network needs next is often not on any item. A page-numbered wine API needs `page=4`; a token API needs the token from the last response. Store it in a small remote keys table, keyed by the query or feed it belongs to, and: - read it at the start of `APPEND` and return `MediatorResult.Success(endOfPaginationReached = true)` when it is `null`; - write it in the **same transaction** as the wines it came with; - delete it with the cached rows on `REFRESH`. ## initialize() and stale caches `suspend fun initialize(): InitializeAction` runs to completion before any loading. Compare the time of the last successful sync with a cache timeout and return: - `SKIP_INITIAL_REFRESH` while the cache is fresh, so cached wines show and no network refresh runs until the UI asks for one; - `LAUNCH_INITIAL_REFRESH` when it is stale. ## The invalidation step The `MediatorResult.Success` KDoc is explicit that it is `load()`'s responsibility to update the dataset **and** trigger `PagingSource.invalidate()`. A database-generated `PagingSource` does the second part itself, because the database invalidates its queries when the observed table changes. A hand-written database `PagingSource` must call `invalidate()` on that change, or the mediator stores rows that do not appear until something else invalidates the source. The new generation resumes around the user because the database's `PagingSource` computes its own refresh key. ## Opting in `RemoteMediator` is annotated `@ExperimentalPagingApi`, a `@RequiresOptIn` marker, in Paging 3.5. So is the primary `Pager` constructor that takes `remoteMediator`. Both the subclass and the code that builds the `Pager` need `@OptIn(ExperimentalPagingApi::class)`, or the build fails. ## Mistakes seen in production - Returning `endOfPaginationReached = true` from `REFRESH` because the first page was short; that ends `APPEND` and `PREPEND` too, so scrolling fetches nothing more until the next refresh. - Writing items and the remote key in separate transactions, so a crash between them leaves a key that skips or repeats a page. - Deleting the old rows on `REFRESH` outside the insert's transaction, so the list flashes empty.

  • The mediator stores each page, but the list never grows past the first page. What do you check first?
    Check what the list's `PagingSource` observes. If the mediator writes to a table that source does not read, or a hand-written source never calls `invalidate()`, no new generation starts. Then check that `REFRESH` did not return `endOfPaginationReached = true`, which also ends appends, and that the `APPEND` key is read from the remote keys table rather than recomputed.
  • Why does a REFRESH in a RemoteMediator usually clear cached rows inside the same transaction as the insert?
    A refresh replaces the cache. If the delete commits first, the `PagingSource` is invalidated by an empty table and the list flashes empty or loses its position. Doing the delete, the insert and the remote-key update in one transaction produces a single invalidation that goes straight from the old rows to the new ones.
  • How do you show cached rows while the network refresh is still running?
    Read `CombinedLoadStates.source.refresh` and `mediator?.refresh` separately. Show the full-screen spinner only when the mediator is loading and the local list is empty; otherwise show the rows with a small refresh indicator. The merged `refresh` property reports `Loading` during the network refresh even when the database already delivered rows.

A shop floor sells only from its shelves; when a shelf runs low a clerk restocks it from the warehouse, and customers see the new bottles because the shelf changed, never because the clerk hands bottles over the counter.

  • RemoteMediator returns the fetched wines straight to the PagingDataAdapter
  • RemoteMediator is stable in Paging 3.5 and needs no opt-in
  • Paging calls RemoteMediator.load(APPEND) on every scroll, not only at the cache's end
  • Returning endOfPaginationReached = true from REFRESH only affects the refresh
  • A hand-written database PagingSource picks up new rows without calling invalidate()