With Paging 3's PagingDataAdapter, how do you show a loading spinner and retry button at the end of a RecyclerView when an append fails?
answer
- a second adapter for one row
- LoadStateAdapter and its loadState
- withLoadStateFooter returns something new
- CombinedLoadStates.append
- retry() keeps the generation
basics
~10 sWrite a LoadStateAdapter that renders LoadState.Loading as a spinner and LoadState.Error as a retry button calling pagingAdapter.retry(), attach it with withLoadStateFooter(), and set the returned ConcatAdapter on the RecyclerView.
solid answer
~30 sPaging reports progress per direction in `CombinedLoadStates`: `refresh`, `prepend` and `append`, each a `LoadState` of `NotLoading`, `Loading` or `Error`. For the footer, subclass `LoadStateAdapter` and implement `onCreateViewHolder(parent, loadState)` and `onBindViewHolder(holder, loadState)`; by default it shows a single row only while the state is `Loading` or `Error`. `pagingAdapter.withLoadStateFooter(footer)` registers a listener that copies `append` into `footer.loadState` and returns a `ConcatAdapter(pagingAdapter, footer)`, and that `ConcatAdapter` is what the RecyclerView must get. The retry button calls `pagingAdapter.retry()`, which re-runs the failed load in the current generation; `refresh()` would rebuild the list. A full-screen spinner or error comes from `loadStateFlow`'s `refresh`.
code
kotlin · 23 linesclass WineFooterAdapter(
private val onRetry: () -> Unit,
) : LoadStateAdapter<WineFooterHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState) =
WineFooterHolder.inflate(parent, onRetry)
override fun onBindViewHolder(holder: WineFooterHolder, loadState: LoadState) {
holder.progress.isVisible = loadState is LoadState.Loading
holder.retryButton.isVisible = loadState is LoadState.Error
}
}
// In the Fragment's onViewCreated
val wineAdapter = WineAdapter() // a PagingDataAdapter<Wine, WineHolder>
binding.wineList.adapter = wineAdapter.withLoadStateFooter(
footer = WineFooterAdapter(onRetry = { wineAdapter.retry() }),
)
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.wines.collectLatest { wineAdapter.submitData(it) }
}
}go deeper
Recall that LoadState is NotLoading, Loading or Error, and that a LoadStateAdapter plus withLoadStateFooter gives a list a loading and retry row.
Explain that withLoadStateFooter returns a ConcatAdapter fed from CombinedLoadStates.append, and when to call retry() versus refresh().
Debug a footer that never appears, a spinner that flashes over cached rows with a RemoteMediator, and an empty state that shows during the first load.
Give the team one shared LoadStateAdapter and one rule for refresh, append and empty states so every paged screen fails and recovers the same way.
## LoadState, per direction Paging tracks every load and exposes the result as **`LoadState`**, a sealed class with three forms: - `LoadState.NotLoading(endOfPaginationReached)`: idle; `endOfPaginationReached = true` means that direction has no more data. - `LoadState.Loading`: a load is in flight. - `LoadState.Error(error)`: the last load failed, with the `Throwable` in `error`. A **`CombinedLoadStates`** carries one per `LoadType`: `refresh` (the first load of a generation), `prepend` and `append`. It also exposes `source` and `mediator` (`LoadStates` for the `PagingSource` and, when one is set, the `RemoteMediator`), plus `isIdle` and `hasError`. `refresh` always reports `endOfPaginationReached = false`. On a `PagingDataAdapter` you read these through `loadStateFlow`, a hot, conflated `Flow<CombinedLoadStates>`, or through `addLoadStateListener`. ## The footer adapter The paging-runtime artifact ships **`LoadStateAdapter<VH>`**, a `RecyclerView.Adapter` that presents one `LoadState` as zero or one row: - you implement `onCreateViewHolder(parent: ViewGroup, loadState: LoadState)` and `onBindViewHolder(holder: VH, loadState: LoadState)`; - its `loadState` property starts as `NotLoading(endOfPaginationReached = false)`, and setting a different value notifies the row inserted, changed or removed; - `displayLoadStateAsItem(loadState)` decides whether the row exists, by default only for `Loading` and `Error`, so the footer disappears when loading succeeds and stays hidden at the end of the list; - `getStateViewType(loadState)` lets you use different view types per state. ## Wiring it in `PagingDataAdapter` offers three helpers: | Helper | Listens to | Returns | |---|---|---| | `withLoadStateHeader(header)` | `prepend` | `ConcatAdapter(header, this)` | | `withLoadStateFooter(footer)` | `append` | `ConcatAdapter(this, footer)` | | `withLoadStateHeaderAndFooter(header, footer)` | both | `ConcatAdapter(header, this, footer)` | The steps for a winery catalogue: 1. Create the `PagingDataAdapter` for wine rows. 2. Create the footer with a retry lambda that calls `wineAdapter.retry()`. 3. Set `recyclerView.adapter = wineAdapter.withLoadStateFooter(footer)`. Setting `wineAdapter` itself instead leaves the listener wired but the footer never attached to the RecyclerView, so it never shows. 4. Collect the ViewModel's flow with `collectLatest { wineAdapter.submitData(it) }` inside `repeatOnLifecycle`. `submitData` suspends while it presents a generation, and its KDoc recommends `collectLatest` so a new `PagingData` promptly replaces the old one. ## retry() versus refresh() - **`retry()`** re-runs loads that ended in `LoadState.Error`, whether a `PagingSource` returned `LoadResult.Error` or a `RemoteMediator` returned `MediatorResult.Error`. It does **not** invalidate the `PagingSource`; already loaded pages stay. - **`refresh()`** creates a new `PagingData` and `PagingSource` (and asks a `RemoteMediator` for a `REFRESH`). It is meant for UI-driven reloads such as swipe-to-refresh, not for a failed page. A failed append wired to `refresh()` discards the loaded pages and reloads the list around the refresh key, just to recover one page. ## The full-screen states The footer covers `append`. The first load is `refresh`: show a centred progress bar while `loadStates.refresh is LoadState.Loading`, and a full-screen error with a retry when it is `LoadState.Error` and the list is empty. With a `RemoteMediator`, `refresh` merges database and network states; read `source.refresh` and `mediator?.refresh` separately when the cached rows should stay visible while the network refresh runs. Two edge cases: - **Placeholders.** When the source reports `itemsAfter` and placeholders are enabled, the footer sits after the placeholder rows; for a network source that reports no counts there are no placeholders. - **Compose screens** read the same `CombinedLoadStates` from the Compose paging integration and place loading items in the lazy list instead, which the Compose lists material covers. ## When the footer misbehaves Most footer bugs come from four places: - **It never appears.** The RecyclerView was given the `PagingDataAdapter` rather than the `ConcatAdapter` that `withLoadStateFooter` returned, or `withLoadStateFooter` was called on a different adapter instance from the one receiving `submitData`. - **It never goes away.** An override of `displayLoadStateAsItem` returns `true` for `NotLoading`, so an idle row stays at the bottom; return `true` for `NotLoading` only when `endOfPaginationReached` is set and you want an explicit end-of-list marker. - **Retry does nothing visible.** The button's lambda captured a different adapter instance from the one on screen, so `retry()` reaches a presenter with nothing to retry. - **The message is unhelpful.** `LoadState.Error.error` is the `Throwable` that was wrapped in `LoadResult.Error` or `MediatorResult.Error`, so the footer can tell a timeout from an HTTP failure when the loader keeps the original exception.
- How do you show an empty-state message only when a paged list is truly empty?Collect `wineAdapter.loadStateFlow` and show it when `refresh` is `LoadState.NotLoading`, `append.endOfPaginationReached` is true and `itemCount` is 0. Checking `itemCount == 0` alone flashes the message during the first load, because the list is empty while `refresh` is still `Loading`.
- With a RemoteMediator, why can a full-screen spinner keyed on loadStates.refresh hide cached rows?`CombinedLoadStates.refresh` merges the `PagingSource` and the `RemoteMediator`, so it reports `Loading` while the network refresh runs even though the database has already delivered rows. Read `source.refresh` and `mediator?.refresh` separately and show the full-screen spinner only while the local list is empty.
- Wiring the footer's retry button to refresh() to reload the failed page
- Setting the PagingDataAdapter on the RecyclerView after calling withLoadStateFooter
- Expecting the footer row to stay visible after the list reaches its end
- Reading loadStates.append to decide when to show a full-screen spinner
- Expecting withLoadStateFooter to also show the first load's full-screen error