Implement the pagination in a few lines,
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.mazenrashed:RxPagination:${LAST_VERSION}'
}
We will use the car example,
Jest implement ListRepository<T>
class CarRepository : ListRepository<Car>{
...
}
Then, you need to override getDataList(page: Int, pageSize : Int) inside the repository
class CarRepository : ListRepository<Car> {
override fun getDataList(page: Int, pageSize : Int): Single<ArrayList<Car>> {
return endPoints.getCars(pageSize, page) //For Example (You need to return your data source here)
}
}
Inehet from RxPagination<T>
class CarsViewModel(carsRepository: CarRepository) :
RxPagination<CarRepository>(carsRepository, PAGE_SIZE, FIRST_PAGE) {
init {
loadDataList()
}
}
Then, you need to override onFetchDataListSubscribed, onFetchDataListError and onFetchDataListSuccess
class CarsViewModel(carsRepository: CarRepository) :
RxPagination<CarRepository>(carsRepository, PAGE_SIZE, FIRST_PAGE) {
init {
loadDataList()
}
override fun onFetchDataListSubscribed() {
//Start fetching data
}
override fun onFetchDataListError(throwable: Throwable) {
}
override fun onFetchDataListSuccess(lastLoadedList: ArrayList<GithubRepository>) {
//You don't need to handle the data, but if you need it, it's available
//This lastLoadedList is the new loaded part.
}
}
To observe the data list, use viewModel.dataList, dataList is a BehaviorRelay<ArrayList<T>>
viewModel
.dataList
.observeOn(AndroidSchedulers.mainThread())
.subscribe { dataList ->
// notify your list adapter here
}
viewModel.loadDataList() //To load the more data
viewModel.reloadDataList() //To reload the data
To access cerrent page
viewModel.page.value //Int
To check if you reach the last page
viewModel.isLastPage.value //Boolean
We welcome contributions !
- ⇄ Pull requests and ★ Stars are always welcome.