skip to content

Paging Library

Jetpack Paging loads a list page by page: a PagingSource fetches, a Pager streams PagingData, and a RemoteMediator fills a Room cache. Asked how an endless list loads, retries and refreshes.

on this pageshow

explore

questions

6

In Paging 3, what do a PagingSource and a Pager each do, and what can PagingSource.load() return?

level: juniorimportance: must knowfreq 72%

answer

  1. one loads, the other streams
  2. LoadParams in, LoadResult out
  3. three LoadResult subclasses
  4. prevKey and nextKey null at the ends
  5. initialLoadSize defaults to 3 x pageSize

basics

~20 s

A PagingSource loads one page per load() call and returns LoadResult.Page, LoadResult.Error for a recoverable failure, or LoadResult.Invalid when its data changed. A Pager combines a PagingConfig with a PagingSource factory and exposes the loads as a Flow<PagingData>.

solid answer

~40 s

`PagingSource<Key, Value>` is the data access piece: Paging calls its suspending `load(params)` with a `LoadParams` (`Refresh`, `Append` or `Prepend`) carrying a `key` and a `loadSize`. It returns `LoadResult.Page(data, prevKey, nextKey)` on success, with a `null` key meaning there is nothing more in that direction; `LoadResult.Error(throwable)` for an expected failure such as no network, which surfaces as `LoadState.Error` and can be retried; or `LoadResult.Invalid()` when it can no longer load consistently. `Pager` is the entry point: give it a `PagingConfig` (only `pageSize` is required) and a `pagingSourceFactory`, and its `flow` emits one `PagingData` per generation, creating a fresh `PagingSource` every time the old one is invalidated.

code

kotlin · 31 lines
kotlin
class WinePagingSource(
    private val api: WineApi,
) : PagingSource<Int, Wine>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Wine> {
        val page = params.key ?: 1
        return try {
            val wines = api.wines(page = page, perPage = 10)
            LoadResult.Page(
                data = wines,
                prevKey = if (page == 1) null else page - 1,
                nextKey = if (wines.isEmpty()) null else page + 1,
            )
        } catch (e: IOException) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Wine>): Int? =
        state.anchorPosition?.let { anchor ->
            val page = state.closestPageToPosition(anchor)
            page?.prevKey?.plus(1) ?: page?.nextKey?.minus(1)
        }
}

class WineListViewModel(api: WineApi) : ViewModel() {
    val wines: Flow<PagingData<Wine>> =
        Pager(PagingConfig(pageSize = 10)) { WinePagingSource(api) }
            .flow
            .cachedIn(viewModelScope)
}

go deeper

for a junior

Recall the split: PagingSource fetches a page, Pager turns pages into a Flow of PagingData. Name the three LoadResult types and say that a null nextKey means the end of the list.

for a middle

Explain LoadParams Refresh, Append and Prepend, where each key comes from, and why the first load asks for three pages' worth of items by default.

for a senior

Show how a page-numbered source breaks when the first load uses loadSize as the server page size, and why load() must return LoadResult.Error instead of throwing.

for a principal

Set the team rule that one Pager lives per ViewModel with a factory that always builds a new PagingSource, and that every source returns LoadResult.Error for expected failures.

## Two pieces, two jobs Jetpack Paging 3 splits paged loading into a part you write and a part the library runs. - **`PagingSource<Key, Value>`** knows how to fetch *one page*. `Key` is whatever identifies a page (an `Int` page number, a `String` token, an item id) and `Value` is the item type, for example `Wine`. - **`Pager`** owns the loading loop. It asks the `PagingSource` for pages as the list is scrolled, collects them into `PagingData`, and exposes a cold `Flow<PagingData<Value>>` through its `flow` property. - **`PagingData`** is one *generation*: a snapshot of a data set that can grow as pages arrive but whose loaded items are never edited in place. When the underlying data changes, the `PagingSource` is invalidated and the `Pager` emits a new `PagingData` backed by a new `PagingSource` from your factory. Because a `PagingSource` instance is single-use, the `Pager` takes a factory lambda, not an instance. Returning the same object from that lambda twice is a bug: an invalidated source stays invalid forever. ## What load() receives `load(params: LoadParams<Key>)` is a `suspend` function, so it can call a suspending network or database API directly. `LoadParams` is sealed: | Subclass | When it is sent | Its `key` | |---|---|---| | `LoadParams.Refresh` | first load, and the first load of every new generation | `initialKey` from the `Pager` the first time, then whatever `getRefreshKey()` returned; may be `null` | | `LoadParams.Append` | the user scrolled near the end | the last page's `nextKey`, never `null` | | `LoadParams.Prepend` | the user scrolled near the start | the first page's `prevKey`, never `null` | `loadSize` is a request, not a contract: the refresh asks for `initialLoadSize` items and every later load asks for `pageSize`. A `PagingSource` may ignore it and still return a valid page. ## What load() returns `LoadResult` is sealed with exactly three subclasses: 1. **`LoadResult.Page(data, prevKey, nextKey)`** on success. Set `prevKey` to `null` on the first page and `nextKey` to `null` on the last page; that is how Paging learns it reached an end, and the matching `LoadState` becomes `NotLoading(endOfPaginationReached = true)`. The optional `itemsBefore` and `itemsAfter` counts enable `null` placeholders. 2. **`LoadResult.Error(throwable)`** for an *expected, recoverable* failure. Paging forwards it to the UI as `LoadState.Error`, and a later `retry()` runs that load again. 3. **`LoadResult.Invalid()`** when the source notices that the data it reads from changed under it. Paging discards pending loads, invalidates this source and starts a new generation. ## Pager and PagingConfig You build the stream once, usually in a ViewModel, and keep that one `Pager`; the class documentation asks for the same `Pager` instance to be reused within a ViewModel. `PagingConfig` takes one required argument and five with defaults (checked in `PagingConfig.kt` for Paging 3.5): - `pageSize`: required, the size Paging requests on append and prepend. - `prefetchDistance`: defaults to `pageSize`; how close to the loaded edge an access must be to trigger the next load. - `enablePlaceholders`: defaults to `true`, but placeholders only appear when the source reports `itemsBefore`/`itemsAfter`. - `initialLoadSize`: defaults to `pageSize * 3`. - `maxSize`: defaults to `PagingConfig.MAX_SIZE_UNBOUNDED`, so pages are never dropped. - `jumpThreshold`: defaults to `COUNT_UNDEFINED`, which disables jumping. The constructor throws `IllegalArgumentException` when placeholders are off and `prefetchDistance` is `0`, and when a bounded `maxSize` is smaller than `pageSize + 2 * prefetchDistance`. ## Mistakes that show up in review - **Throwing from `load()`.** An exception that escapes `load()` is not turned into `LoadState.Error`; catch expected failures and return `LoadResult.Error` instead. - **Passing `loadSize` to a page-numbered API.** With `pageSize = 10`, the refresh asks for 30 items. If page 1 is fetched with a size of 30 and page 2 with a size of 10, page 2 repeats items 11 to 20. Keep the server page size fixed or set `initialLoadSize = pageSize`. - **Returning the same `nextKey` twice in a row.** Paging fails fast with an `IllegalStateException` saying the same value was passed as `nextKey` in two sequential pages, unless the source overrides `keyReuseSupported`. - **Building a new `Pager` on every call** of a repository function, which restarts loading from scratch each time. Once these are right, the rest of a paged screen, caching the stream, showing load states and refreshing, builds on the same two pieces.

  • When should load() return LoadResult.Invalid rather than LoadResult.Error?
    `LoadResult.Error` means this load failed but the source is still usable, so a retry makes sense. `LoadResult.Invalid` means the source's view of the data is no longer consistent, for example a LIMIT/OFFSET query that notices the table changed while it was loading. Paging then drops pending loads, invalidates the source and asks the factory for a new one.
  • Why does the Pager take a lambda that creates a PagingSource instead of a PagingSource instance?
    A `PagingSource` represents one snapshot. Once `invalidate()` is called it never becomes valid again, so every new generation, after a refresh, an invalidation or `LoadResult.Invalid`, needs a brand-new instance. The `pagingSourceFactory` lambda lets the `Pager` create one each time; returning a cached instance from it hands Paging an already invalid source.

  • Throwing the IOException from load() so Paging shows a retry state
  • Returning LoadResult.Invalid for a network timeout
  • Assuming the first load requests pageSize items
  • Reusing one PagingSource instance across refreshes
  • Passing params.loadSize as the server page size for page-number keys
open as a page

In Paging 3, why does a ViewModel end its Pager.flow chain with cachedIn(viewModelScope), and where do map and insertSeparators go relative to it?

level: middleimportance: must knowfreq 62%

basics

~20 s

cachedIn(viewModelScope) shares the PagingData stream and keeps its loaded pages alive in the ViewModel, so a rotated screen gets them back instead of reloading. Put map, filter and insertSeparators before it so their results are cached too.

open as a page

In Paging 3, what does PagingSource.getRefreshKey() decide, and how do you implement it for a page-numbered wine catalogue API?

level: middleimportance: should knowfreq 48%

basics

~20 s

getRefreshKey() picks the key a new generation's first load starts from after an invalidation, so the list reloads where the user is. For page numbers, take the page closest to state.anchorPosition and return prevKey + 1 or nextKey - 1.

open as a page

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%

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.

open as a page

As Android lead, should a wine catalogue page through a RemoteMediator into Room or straight from the network with a PagingSource, and what does each choice commit the team to?

level: principalimportance: should knowfreq 26%

basics

~20 s

Use a RemoteMediator into Room when the list must work offline, survive process death or reflect local edits; page straight from the network when results are throwaway. The mediator costs an experimental API, a schema with remote keys and harder tests.

open as a page