Picture of book pages

Android Paging3 cheat sheet

This post is a basic set up for using Paging3 to page though data progressively when requesting a large dataset.

It relies on coroutines and Flow for handling concurrency, but Paging3 also has support for using RxJava, or a ListenableFuture from Guava.

I am also showing an example using jetpack Compose, but support for using a View-based RecyclerView (based on a PagingDataAdapter).

Dependency Injection is mentioned but is not impactful on the subject.

Stack info

Here is the list of tech choices made for this implementation example

  • Paging3
  • Kotlin
  • gradle build file
  • Dependency Injection with Hilt
  • Jetpack Compose
  • Flow
  • Coroutines
  • Repository and DAO
  • LazyColumn

Using Paging3 to page a data request Cheat sheet

Dependencies
implementation("androidx.paging:paging-runtime:$paging_version")
// versions are currently not aligned for paging-compose
implementation("androidx.paging:paging-compose:3.3.2")

// needed for cachedIn() operator
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
DAO interface
@Query(« Select * from mydata ») 
fun loadAllPaged() : PagingSource<Int, MyDataEntity>
Repository class
// inject myDao with DI
fun loadAllMyDataEntityPaged() : PagingSource<Int, MyDataEntity> = myDao.loadAllPaged()
UseCase
// inject myRepository with DI
fun call(): Flow<PagingData<MyData>> 
= Pager(pagingConfig= PagingConfig(pageSize = 10, prefetchDistance = 20)) {
myRepository.loadAllMyDataEntityPaged()

}
.flow
.map { value : PagingData<MyDataEntity> ->
value.map { anEntity ->
anEntity.toDomainModel()
}
}
ViewModel
// inject myUseCase with DI
        val pagedDataItems : Flow<PagingData<MyData>> = myUseCase.call() 
.cachedIn(viewModelScope) // preserve loaded data in case of configuration change
@Composable function
// pass in viewModel or some handle to the Flow object
val pagedItems : LazyPagingItems<MyData> 
= viewModel.pagedDataItems.collectAsLazyPagingItems()

LazyColumn() {
items(
count = pagedItems.itemCount,
key = pagedItems.itemKey { it.id },
contentType = pagedItems.itemContentType { «MyItems» }
) { index : Int ->
val item : MyData? = pagedItems[index]
if (item!= null) { MyIndividualItemComposable(data = item) }
}
}

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *