skip to content

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%

answer

  1. the first key of the next generation
  2. invalidate, refresh() or a jump
  3. PagingState.anchorPosition
  4. closestPageToPosition, prevKey + 1
  5. null sends the list back to the top

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.

solid answer

~40 s

Every time a generation ends, through `PagingSource.invalidate()`, `LoadResult.Invalid`, a UI `refresh()` or a jump past `jumpThreshold`, Paging calls `getRefreshKey(state)` and passes the result to the new source's `LoadParams.Refresh.key`. The `PagingState` carries the loaded `pages`, the `config` and `anchorPosition`, the most recently accessed index. For an `Int` page key, find `state.closestPageToPosition(anchor)` and return `prevKey?.plus(1) ?: nextKey?.minus(1)`. Returning `null` is legal and means "let `load()` choose its default", which for most sources is page 1, so a pull-to-refresh deep in the list jumps the user back to the top. In Paging 3.5 the PagingState also offers `closestItemToPosition` and, since 3.4.0, `closestItemAroundPosition` for item-keyed sources.

code

kotlin · 16 lines
kotlin
override fun getRefreshKey(state: PagingState<Int, Wine>): Int? {
    val anchor = state.anchorPosition ?: return null
    val anchorPage = state.closestPageToPosition(anchor) ?: return null
    // prevKey == null -> first page; nextKey == null -> last page
    return anchorPage.prevKey?.plus(1) ?: anchorPage.nextKey?.minus(1)
}

@Test
fun refreshKeyIsTheAnchorPage() = runTest {
    val pager = TestPager(PagingConfig(pageSize = 10), WinePagingSource(FakeWineApi()))
    pager.refresh()          // page 1
    pager.append()           // page 2
    pager.append()           // page 3
    val state = pager.getPagingState(anchorPosition = 15)
    assertEquals(2, WinePagingSource(FakeWineApi()).getRefreshKey(state))
}

go deeper

for a junior

Recall that getRefreshKey picks where a reloaded list starts, using PagingState.anchorPosition, and that returning null sends the list back to its default start.

for a middle

Walk through the page-number recipe with closestPageToPosition and prevKey + 1, and list the events that start a new generation and so call this method.

for a senior

Diagnose a list that jumps to the top after every pull-to-refresh or database write, and show how TestPager and getPagingState pin the refresh key in a unit test.

for a principal

Make a correct refresh key part of the review checklist for every hand-written PagingSource, since it decides whether invalidation-driven updates feel seamless or jarring.

## What the refresh key is for A `PagingData` is a snapshot. When the data behind it changes, Paging does not patch the snapshot; it throws the generation away and starts a new one with a new `PagingSource`. The first load of that new generation is a `LoadParams.Refresh`, and its `key` comes from **`getRefreshKey(state: PagingState<Key, Value>): Key?`**, an abstract method every `PagingSource` must implement. Paging starts a new generation in these cases: - the source calls `invalidate()` itself, or a library that owns it does (a database-backed source invalidates when its table changes); - `load()` returned `LoadResult.Invalid`; - the UI called `refresh()` on the `PagingDataAdapter`, for example from swipe-to-refresh; - the user scrolled past more than `PagingConfig.jumpThreshold` placeholders on a source with `jumpingSupported = true`. The very first load of the stream does not use it: that key is the `initialKey` given to the `Pager`. ## What PagingState gives you | Member | What it holds | |---|---| | `pages` | the `LoadResult.Page`s loaded in the ending generation | | `anchorPosition` | the most recently accessed index, counting placeholders; `null` if nothing was accessed yet | | `config` | the `PagingConfig`, including `initialLoadSize` | | `closestPageToPosition(anchorPosition)` | the loaded page nearest that index | | `closestItemToPosition(anchorPosition)` | the loaded item nearest that index | | `closestItemAroundPosition(anchorPosition, predicate)` | the nearest loaded item that matches a predicate, added in Paging 3.4.0 | `anchorPosition` is the last index the UI *accessed*, which, because items are accessed as they bind, is usually the top-most or bottom-most row in the viewport rather than its exact middle. ## Implementing it for page numbers A wine catalogue API serves `?page=N` with ten wines per page, so `Key` is `Int`. The documented recipe: 1. Read `state.anchorPosition`; if it is `null`, return `null`. 2. Find the anchor's page with `state.closestPageToPosition(anchor)`. 3. That page's own number is `prevKey + 1`, or `nextKey - 1` when it is the first page and `prevKey` is `null`. 4. If both keys are `null` (a single-page list), return `null`. The refresh load then fetches that page, and because the refresh asks for `initialLoadSize` items, a source that serves exactly that much centred on the key fills the viewport around the user. For other key shapes: - **Position keys**: the source documentation suggests `((state.anchorPosition ?: 0) - state.config.initialLoadSize / 2).coerceAtLeast(0)`, centring the refresh on the anchor. - **Item keys** (an `after=<id>` API): take the id of `closestItemToPosition(anchor)`, or use `closestItemAroundPosition` when only some items can serve as anchors, for example skipping rows that are not real wines. ## What goes wrong - **Returning `null` everywhere.** It compiles and works on first load, but every invalidation restarts from page 1 and the list jumps to the top after a refresh or a database write. - **Returning the anchor page's `nextKey`.** The refresh then starts one page after the user's rows, so they are missing from the first refreshed load and the list visibly shifts while that page is prepended back. - **Ignoring `anchorPosition` being `null`.** The anchor is `null` until something has been accessed; force-unwrapping it crashes a refresh that fires before the first bind. - **Forgetting it matters for jumping.** A source that sets `jumpingSupported = true` relies on `getRefreshKey()` to land the user where they jumped to, as the `jumpThreshold` documentation notes. Two release notes touch this method's input: Paging 3.4.0 added `closestItemAroundPosition`, and 3.5.1 fixed an `anchorPosition` that came out too large when refreshing a list with separators while scrolling into placeholders. Paging 3.5.3 includes both. ## Refresh keys and LoadResult.Invalid A source that detects inconsistent data mid-load returns `LoadResult.Invalid`, and Paging immediately starts a new generation, again through `getRefreshKey()`. A good refresh key is therefore what keeps that self-healing invisible to the user: the replacement source loads the same neighbourhood and the list differ animates only what actually changed. ## Testing it The `paging-testing` artifact's `TestPager` drives a single `PagingSource`: call `refresh()`, then `append()` a few times, build a state with `getPagingState(anchorPosition)`, and assert what `getRefreshKey()` returns for it.

  • How do refresh() and retry() on a PagingDataAdapter differ with respect to getRefreshKey()?
    `refresh()` ends the generation: Paging creates a new `PagingSource` and its first load uses the key `getRefreshKey()` returns. `retry()` keeps the current generation and only re-runs loads that failed with `LoadState.Error`, so `getRefreshKey()` is not involved.
  • Why might an item-keyed source use closestItemAroundPosition instead of closestItemToPosition?
    `closestItemToPosition` returns whatever loaded item is nearest the anchor, which may be a row the API cannot use as a key. `closestItemAroundPosition(anchorPosition, predicate)`, added in Paging 3.4.0, returns the nearest loaded item matching the predicate, so the refresh starts from an item the backend can page from.

  • Returning null from getRefreshKey because refresh always starts at page 1 anyway
  • Thinking getRefreshKey runs before the very first load of the stream
  • Returning the anchor page's nextKey as the refresh key
  • Treating anchorPosition as the index of the first visible row
  • Believing retry() calls getRefreshKey to rebuild the list

Assumes Paging 3.5.3; closestItemAroundPosition arrived in 3.4.0 and 3.5.1 fixed an oversized anchorPosition with separators.