In Paging 3, what do a PagingSource and a Pager each do, and what can PagingSource.load() return?
answer
- one loads, the other streams
- LoadParams in, LoadResult out
- three LoadResult subclasses
- prevKey and nextKey null at the ends
- initialLoadSize defaults to 3 x pageSize
basics
~20 sA 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 linesclass 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
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.
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.
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.
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