Android development / Intermediate: state, data, and inclusive features / Lesson 14
Paging sources and bounded lists
Load a bounded list in pages and distinguish page keys, refresh, errors and presentation state.
On this page
Lesson goals
- Implement a simple offset-based PagingSource.
- Create a Pager with an explicit page size.
- Test boundaries and refresh behavior.
Define the paging contract
Paging avoids presenting an entire large data set at once by loading portions as needed. A source must define key meaning, ordering and how it identifies the end. The UI still needs loading, empty and error states. Decide whether the source is a local snapshot or a changing service before choosing a key; an offset suitable for a fixed list may not remain stable when remote records change.
Build a bounded source
This illustrative source pages through a fixed in-memory list using offsets. It clamps the starting offset, returns a bounded slice and stops when it reaches the end. Returning null from getRefreshKey restarts at the initial position; it is simple but does not preserve an anchor. The host needs the appropriate Android Paging dependency and a stable input snapshot.
import androidx.paging.PagingSource
import androidx.paging.PagingState
class NamesSource(private val names: List<String>) : PagingSource<Int, String>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, String> {
val start = (params.key ?: 0).coerceIn(0, names.size)
val end = (start + params.loadSize).coerceAtMost(names.size)
return LoadResult.Page(
data = names.subList(start, end),
prevKey = if (start == 0) null else (start - params.loadSize).coerceAtLeast(0),
nextKey = if (end == names.size) null else end
)
}
override fun getRefreshKey(state: PagingState<Int, String>): Int? = null
}
An empty list yields an empty page with no next key.
Keys represent list offsets, not page numbers; nextKey is the end of the returned slice.
Create a pager
The Pager creates a fresh source when needed and exposes a flow of PagingData. A real owner must collect and present it with lifecycle-aware behavior appropriate to its UI, including load states and retry. This fragment does not fetch a network service or claim any device execution. Avoid mutating the source list behind the source without an explicit invalidation strategy.
import androidx.paging.Pager
import androidx.paging.PagingConfig
fun namesPager(names: List<String>) = Pager(
config = PagingConfig(pageSize = 20, enablePlaceholders = false),
pagingSourceFactory = { NamesSource(names) }
).flow
The flow provides paged data when collected by a configured host.
The factory creates a source for the supplied snapshot and disables placeholders for the example.
Plan errors and refresh
A network or database source should convert expected failures into appropriate load results, propagate cancellation correctly and define how refresh finds its position. Do not copy this fixed-list key strategy blindly into a changing API. Confirm the serviceโs ordering, cursor and duplicate policy, and show a retry action only when the operation can safely be retried.
Verify page boundaries
Test an empty list, a list smaller than the requested load and a list spanning several pages. Check no items are skipped or duplicated at boundaries, and test refresh and invalidation. Then verify loading, error and accessibility behavior in the actual Android UI. A source unit test is useful but does not prove native scrolling, lifecycle collection or remote consistency.
Common errors and fixes
Records are skipped between pages.
- Why it happens
- A page-number calculation assumes an unchanged load size.
- How to fix it
- Use keys that match the source contract, such as offsets or stable cursors.
- Prevent it next time
- Test varying load sizes and boundary values.
Refresh unexpectedly returns to the beginning.
- Why it happens
- The source returns no refresh key.
- How to fix it
- Implement an anchor-aware key when the source supports it.
- Prevent it next time
- Document and test refresh position.
The UI appears empty during a failed load.
- Why it happens
- Load errors are not represented separately from empty data.
- How to fix it
- Present an appropriate error and retry path.
- Prevent it next time
- Test empty and failure states independently.
2 practice exercises
1. Why does nextKey use end rather than a page number?
Show worked solution
The example key is a list offset. The end of the current slice is the start of the next slice, even if the requested load size changes.
2. Does a null refresh key preserve the current scroll anchor?
Show worked solution
No. This simple source restarts from its initial key. An anchor-aware strategy requires a key that the source can safely reconstruct.
Key takeaways
- Define key, ordering and end-of-data contracts.
- Treat refresh and load failures explicitly.
- Test source boundaries and the actual UI separately.