✨ A simple and concise implementation of a dynamic pager for Jetpack Compose with no strings attached ✨
If you're using Version Catalog, configure the dependency by adding the below lines to your libs.versions.toml
[versions]
simplepager = "<version>"
[libraries]
simplepager = { module = "com.github.CookieDinner:SimplePager", version.ref = "simplepager" }Add the dependency into your module's build.gradle.kts
dependencies {
implementation("com.github.CookieDinner:SimplePager:$version")
// Or if you're using the Version Catalog
implementation(libs.simplepager)
}1. Create the Pager instance in your ViewModel and a variable containing the StateFlow returning the paged items
private val pager = Pager(
config = PagerConfig(
pageSize = 20,
prefetchDistance = 20,
firstPageIndex = 0,
onlyDistinctItems = true,
deactivatePagerOnEndReached = true
),
coroutineScope = viewModelScope
) { nextPage, pageSize ->
// Function returning a Flow<Result<List<T>>>
}
val pagedList = pager.lazyPagingItemsFlowfun example(
page: Int,
pageSize: Int
): Flow<Result<List<Item>>> {
return flow {
emit(/* Specified page of your list */)
}.asResult()
}3. Observe the paged list and use it in your LazyColumn / LazyRow using the items extension provided by the library
val list by viewModel.pagedList.collectAsStateWithLifecycle()
LazyColumn {
items(list) {
//...
}
}pager.resetPager()