Loading lists page by page
Paging 3 has three pieces:
- PagingSourcePagingSource (Paging 3)The Paging 3 class that loads one page of data for a key and tells the library the keys of the previous and next pages.Open in glossary →: knows how to load one page. You get a key (like page 3) and return the items plus the keys for the previous and next pages.
Pager: wraps the source and produces aFlow<PagingData>, a stream of “the list so far”, which grows as more pages load.- The UI:
collectAsLazyPagingItems()gives you a list forLazyColumn. When the user scrolls near the end, Paging loads the next page by itself.
Two lines make it work well:
cachedIn(viewModelScope)in the ViewModel keeps the loaded pages when the screen rotates. Without it, rotation starts again from page 1.loadStatetells you whether the first page is loading, failed, or the end was reached, so you can show a spinner, an error with Retry, or nothing.
PagingSource<Key, Value>.load(params) returns LoadResult.Page(data, prevKey, nextKey), LoadResult.Error or LoadResult.Invalid; getRefreshKey(state) picks the key to reload around the user’s position after invalidation (typically from state.anchorPosition), which is what keeps scroll position when data changes. Pager(PagingConfig(pageSize, prefetchDistance, enablePlaceholders, maxSize)) produces Flow<PagingData>; apply map/filter/insertSeparators and then cachedIn(viewModelScope) last, so transformations aren’t re-run and rotation reuses pages (a PagingData can only be collected once). In Compose, collectAsLazyPagingItems() + items(count, key = lazyPagingItems.itemKey { it.id }) gives stable keys; loadState.refresh, .append and .source/.mediator drive UI. For offline-first lists, make Room the single source of truth: the DAO returns a PagingSource (auto-invalidated on table changes) and a RemoteMediator loads network pages into the database (including a remote-keys table for cursors), so the UI never reads the network directly and works offline.
class OrdersPagingSource(private val api: OrdersApi) : PagingSource<String, Order>() {
override suspend fun load(params: LoadParams<String>): LoadResult<String, Order> = try {
val page = api.orders(cursor = params.key, limit = params.loadSize) // null key = first page
LoadResult.Page(data = page.items, prevKey = null, nextKey = page.nextCursor)
} catch (e: IOException) {
LoadResult.Error(e)
} catch (e: HttpException) {
LoadResult.Error(e)
}
// After a refresh, start again from the first page (a cursor API can't jump to the middle)
override fun getRefreshKey(state: PagingState<String, Order>): String? = null
}
@HiltViewModel
class OrdersViewModel @Inject constructor(api: OrdersApi) : ViewModel() {
val orders: Flow<PagingData<Order>> =
Pager(PagingConfig(pageSize = 30, prefetchDistance = 10)) { OrdersPagingSource(api) }
.flow
.cachedIn(viewModelScope) // survives rotation
}
@Composable
fun OrdersScreen(viewModel: OrdersViewModel = hiltViewModel()) {
val orders = viewModel.orders.collectAsLazyPagingItems()
when (val refresh = orders.loadState.refresh) {
is LoadState.Loading -> FullScreenSpinner()
is LoadState.Error -> ErrorScreen(refresh.error, onRetry = orders::retry)
is LoadState.NotLoading -> LazyColumn {
items(count = orders.itemCount, key = orders.itemKey { it.id }) { index ->
orders[index]?.let { OrderRow(it) } ?: OrderRowPlaceholder()
}
if (orders.loadState.append is LoadState.Loading) item { RowSpinner() }
if (orders.loadState.append is LoadState.Error) item { RetryRow(onRetry = orders::retry) }
}
}
}loadasks the API for one page, using the cursor the previous page returned.nextKey = nullmeans “no more pages”.- Errors become
LoadResult.Error, which the UI sees asLoadState.Errorwith a Retry button, instead of crashing. cachedIn(viewModelScope)keeps pages in the ViewModel, which survives rotation.itemKey { it.id }gives each row a stable key, so Compose doesn’t confuse rows when pages load.loadState.refreshis about the first load;loadState.appendis about loading more at the end.
Tap the line with the bug.
@Composable
fun OrdersScreen(api: OrdersApi) {
val orders = remember {
Pager(PagingConfig(pageSize = 30)) { OrdersPagingSource(api) }.flow
}.collectAsLazyPagingItems()
LazyColumn {
items(orders.itemCount) { index -> orders[index]?.let { OrderRow(it) } }
}
}Hint: What happens to remember on rotation, and where else could the Pager live?
remember is forgotten when the activity is recreated, so every rotation builds a new Pager and loads from page 1, losing the user’s place and repeating network requests. There’s also no cachedIn, and no item keys.
Create the flow in a ViewModel, which survives rotation, and cache it there:
class OrdersViewModel(api: OrdersApi) : ViewModel() {
val orders = Pager(PagingConfig(pageSize = 30)) { OrdersPagingSource(api) }
.flow
.cachedIn(viewModelScope)
}Offline-first with RemoteMediator
@OptIn(ExperimentalPagingApi::class)
class OrdersMediator(
private val api: OrdersApi,
private val db: ShopDatabase,
) : RemoteMediator<Int, OrderEntity>() {
override suspend fun load(loadType: LoadType, state: PagingState<Int, OrderEntity>): MediatorResult {
val cursor = when (loadType) {
LoadType.REFRESH -> null
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> db.remoteKeys().get("orders")?.nextCursor
?: return MediatorResult.Success(endOfPaginationReached = true)
}
return try {
val page = api.orders(cursor = cursor, limit = state.config.pageSize)
db.withTransaction { // one transaction: no empty flash
if (loadType == LoadType.REFRESH) {
db.orders().clearAll()
db.remoteKeys().clear("orders")
}
db.remoteKeys().put(RemoteKey("orders", page.nextCursor))
db.orders().insertAll(page.items.map { it.toEntity() })
}
MediatorResult.Success(endOfPaginationReached = page.nextCursor == null)
} catch (e: IOException) {
MediatorResult.Error(e) // cached rows stay visible
}
}
}
val orders = Pager(
config = PagingConfig(pageSize = 30),
remoteMediator = OrdersMediator(api, db),
pagingSourceFactory = { db.orders().pagingSource() }, // Room is the single source of truth
).flow.cachedIn(viewModelScope)The UI only ever reads Room’s PagingSource. Network failures leave cached rows on screen with an append error; a pull-to-refresh calls refresh(), which runs the mediator with REFRESH. Override initialize() to return SKIP_INITIAL_REFRESH when the cache is fresh enough, so opening the screen doesn’t always hit the network.
Predict the output
The orders list shows 120 loaded orders and the user has scrolled to order 90. The PagingSource is invalidated (the user deleted an order). getRefreshKey returns null. Where does the list end up?
After invalidation, Paging creates a new PagingSource and asks getRefreshKey where to start. null means 'the first page', so the list reloads from the top and the user loses their place. For APIs that can load around a position (page numbers, offsets, or a Room PagingSource, which does this for you), return a key near state.anchorPosition instead.
PagingSource.load→Page(data, prevKey, nextKey)/Error/Invalid;getRefreshKeyfromanchorPositionpreserves scroll after invalidation.Pager(PagingConfig(pageSize, prefetchDistance, maxSize))→ transformations →cachedIn(viewModelScope)last;PagingDatais single-collection.- Compose:
collectAsLazyPagingItems(),itemKey { it.id },loadState.refresh/append,retry(). - Offline-first: Room
PagingSourceas single source of truth +RemoteMediator(remote keys table, REFRESH clear+insert in one transaction,initialize()to skip refreshes).
Check this part
What does cachedIn(viewModelScope) prevent?
What does nextKey = null mean in a LoadResult.Page?
In an offline-first paged list, where does the UI read from?
Why clear and insert in one transaction during REFRESH?