Pagination with Paging3 covered in previous repository
!
Here we will continue to implement offline pagination.
Module Level -
kotlin("kapt")
id("com.google.dagger.hilt.android")
// Hilt
implementation("com.google.dagger:hilt-android:2.51")
kapt("com.google.dagger:hilt-android-compiler:2.51")
// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0")
// LiveData
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.7.0")
//Retrofit
implementation ("com.squareup.retrofit2:retrofit:2.9.0")
implementation ("com.squareup.retrofit2:converter-gson:2.9.0")
//Room
implementation("androidx.room:room-runtime:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")
implementation("androidx.room:room-paging:2.6.1")
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:2.6.1")
//Coroutines
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
// Paging3
implementation ("androidx.paging:paging-runtime:3.2.1")
// Allow references to generated code
kapt {
correctErrorTypes = true
}
Project Level -
id("com.google.dagger.hilt.android") version "2.51" apply false
- Write Logic to fetch the page.
- Create the Room DB Module inside di package.
- Save the quotes in DB.
- Define quotes table to manage quotes inside room databse.
- Another table is needed to maintain the
Previous Keys
andNext Keys
. (With quote id)- Define remote keys table to manage keys inside room database.
- This table is used to calculate the
Previous Keys
andNext Keys
.
- We will use this remote keys table to fetch the data from quote table in pages.
Now We have implemented required setup of Room Database for Paging.
Now create the Remote Mediator class to handle different states -
- PREPEND,
- APPEND,
- REFRESH.
Calculate the current page based on the loadType.
- Using paging state you can calculate the page number.
- For append, you can get the last page's last record to get the next key.
- For prepend, you can use first page in paging state for previous key.
- Refresh and First Time Load is similar - it uses Anchor Position to evaluate the current page number.