Originally published on Medium:
https://medium.com/@supsabhi/mastering-pagination-in-jetpack-compose-paging-3-vs-snapshotflow-8193410eb991?sharedUserId=supsabhi
We’ve all been there: a list of 1,000 items and a phone that wants to explode. Scrolling through a never-ending list is one of the most common patterns in modern apps: feeds, product lists, chats, you name it. If you’ve ever tried to load thousands of items in a Jetpack Compose list, you know the struggle. Your app starts lagging, memory usage skyrockets, and suddenly your smooth, modern UI feels like it’s running on a potato. That’s where pagination comes to the rescue. Pagination isn’t just a feature; it’s a performance necessity.
If you’re building with Jetpack Compose today, you essentially have two main ways to handle this: lean on the robust Paging 3 library or roll your own pagination using tools like snapshotFlow and LazyColumn.
In this article, we’ll walk through both approaches, look at real code, and discuss when each one makes sense for your app.
Why Pagination Matters in Modern Android Apps
Before we dive into the how, let’s talk about the why. Imagine you’re building a social media app with thousands of posts, or an e-commerce app with endless product listings. Loading everything at once would be a disaster for your users’ experience and your server’s health.Pagination solves this by:
- Reducing memory consumption by loading data in chunks
- Improving app performance with faster initial load times
- Saving bandwidth by fetching only what users need
- Creating smoother scrolling experiences without janky animations
In Compose, pagination revolves around a few key building blocks:
- LazyColumn / LazyVerticalGrid to render large lists efficiently
- Paging 3 (Pager, PagingSource, PagingData) when you want a robust, scalable solution
- snapshotFlow when you want lightweight, custom pagination behavior without bringing in the whole Paging stack
Approach 1: Pagination with Paging 3
Paging 3 is Google’s official library to load and display paged data from local or remote sources. It’s feature-rich, battle-tested, and integrates beautifully with Jetpack Compose. Think of it as the Swiss Army knife of pagination.
Paging 3 isn’t just about loading data in chunks. It’s a complete ecosystem that handles:
- Automatic loading indicators
- Error handling with retry mechanisms
- Efficient memory management with in-memory caching
- Support for multiple data sources (network, database, or both)
- Seamless integration with Room database
- Handling of data transformations and separators
While using Paging 3, you generally work with three main pieces:
- PagingSource: Knows how to load a single page of data
- Pager: Wraps your PagingSource and exposes a Flow>
- collectAsLazyPagingItems(): Turns that PagingData flow into something your LazyColumn can consume in Compose
Setting Up Paging 3
First, add the necessary dependencies to your build.gradle.kts:
dependencies {
implementation("androidx.paging:paging-runtime:3.2.1")
implementation("androidx.paging:paging-compose:3.2.1")
}
Creating a PagingSource
The PagingSource is where the magic begins. It’s responsible for loading pages of data from your data source. Here’s a real-world example fetching user data from an API:
class UserPagingSource(
private val apiService: ApiService
) : PagingSource<Int, User>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, User> {
return try {
val page = params.key ?: 1
val response = apiService.getUsers(
page = page,
pageSize = params.loadSize
)
LoadResult.Page(
data = response.users,
prevKey = if (page == 1) null else page - 1,
nextKey = if (response.users.isEmpty()) null else page + 1
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, User>): Int? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
}
}
}
Few points to understand here are:
- load() is called automatically when more data is needed
- params.key represents the page number (null for the first load)
- prevKey and nextKey tell Paging 3 how to navigate between pages
- getRefreshKey() determines where to restart loading after a refresh
Implementing the Repository
Create a repository to expose the paging data as a Flow:
class UserRepository(private val apiService: ApiService) {
fun getUsersStream(): Flow<PagingData<User>> {
return Pager(
config = PagingConfig(
pageSize = 20,
enablePlaceholders = false,
prefetchDistance = 5
),
pagingSourceFactory = { UserPagingSource(apiService) }
).flow
}
Few points to understand here are:
- enablePlaceholders: Whether to show placeholders for unloaded content
- pageSize: How many items to load per page
- prefetchDistance: How many items before the end should trigger loading
ViewModel Integration
Your ViewModel should expose the paging data and manage the UI state:
class UserViewModel(
private val repository: UserRepository
) : ViewModel() {
val usersFlow: Flow<PagingData<User>> = repository.getUsersStream()
.cachedIn(viewModelScope)
}
The cachedIn() operator is crucial — it caches the PagingData in the ViewModel scope, preventing unnecessary reloads during configuration changes.
Implementation of Compose Part in Screen
@Composable
fun UserListScreen(viewModel: UserViewModel = viewModel()) {
val users = viewModel.usersFlow.collectAsLazyPagingItems()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(count = users.itemCount) { index ->
users[index]?.let { user ->
UserListItem(user = user)
}
}
when {
users.loadState.refresh is LoadState.Loading -> {
item {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
}
users.loadState.refresh is LoadState.Error -> {
val error = (users.loadState.refresh as LoadState.Error).error
item {
ErrorItem(
message = error.localizedMessage ?: "Unknown error",
onRetry = { users.retry() }
)
}
}
users.loadState.append is LoadState.Loading -> {
item {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
}
users.loadState.append is LoadState.Error -> {
val error = (users.loadState.append as LoadState.Error).error
item {
ErrorItem(
message = error.localizedMessage ?: "Unknown error",
onRetry = { users.retry() }
)
}
}
}
}
}
You can implement some advanced features like inserting separators and multi-layer caching of data.
Things to Take Care of While Using Paging 3
Not Using cachedIn() with Paging 3: Without cachedIn(), you’ll reload data on every configuration change.
Forgetting Error States: Always handle errors gracefully with retry options.
Loading Too Much Data Per Page: Sweet spot: 20–30 items per page.
Not Using Stable Keys: Always provide stable, unique keys.
Let’s Deep Dive into Approach 2: SnapshotFlow
Sometimes you don’t need the full power of Paging 3. For smaller or simpler lists, or when you want tight control over behavior, you can implement pagination yourself using LazyColumn and snapshotFlow.
snapshotFlow offers a lightweight, Compose-native approach.
Why Choose SnapshotFlow?
SnapshotFlow is perfect when you:
- Have a simpler pagination requirement
- Want complete control over the loading logic
- Don’t need complex caching mechanisms
- Prefer a minimalist approach without additional dependencies
- Are working with local data sources
What is snapshotFlow?
snapshotFlow converts Compose state reads into a cold Flow, emitting a new value whenever that state changes. It’s usually used inside a LaunchedEffect to observe state changes like scroll positions, current page, or user inputs.
snapshotFlow is great when you need a continuous stream of updates and want to take advantage of Flow operators like debounce, map, or distinctUntilChanged
How to implement pagination using snapshotFlow is shown in detail in github repository.
https://github.com/supsabhi/Pagination_jetpackCompose.git
Paging 3 vs snapshotFlow/manual: which one should you use?
Both approaches are valid, and you’ll probably use each of them in different parts of the same app.
Choose Paging 3 When:
- You need robust error handling and retry mechanisms out of the box
- Your app requires offline-first functionality with Room database
- You want automatic loading state management
- You’re dealing with complex multi-source data (network + database)
- You need features like data transformations and separators
- You prefer battle-tested, officially supported solutions
Choose SnapshotFlow When:
- You have simple pagination requirements
- You want minimal dependencies and a smaller APK size
- You need complete control over loading logic
- You’re comfortable managing loading states manually
- You’re working primarily with in-memory data
- You want a pure Compose solution without additional libraries
Wrapping Up
Pagination in Jetpack Compose doesn’t have to be intimidating. Whether you choose the comprehensive Paging 3 library or the lightweight snapshotFlow approach, you now have the tools to implement smooth, efficient pagination in your apps.
Quick recap:
- Use Paging 3 for complex, production apps with multiple data sources
- Use snapshotFlow for simpler requirements and more control
- Always handle loading and error states gracefully
- Optimize with proper keys, caching, and debouncing
- Test your implementation thoroughly
The best approach depends on your specific needs, but with both techniques in your toolkit, you’re ready to handle any pagination challenge that comes your way.
Now go forth and paginate! Your users (and your app’s performance) will thank you
GitHub Repository for Hands-On Reference
To make this article more practical and hands-on, I’ve published a public GitHub repository that demonstrates everything discussed above.
The goal of this project is not just to “fetch data and display”, but to show how pagination can be done in different ways in an Android application using Ktor,Coin.
📂 GitHub Repository:
https://github.com/supsabhi/Pagination_jetpackCompose.git
Top comments (0)