Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android - How to transform from List<T> to Observable<PageList<T>> for androidx paging library
package com.lahaus.utils.extensions
import androidx.paging.DataSource
import androidx.paging.PagedList
import androidx.paging.PositionalDataSource
import androidx.paging.RxPagedListBuilder
import io.reactivex.Observable
fun <T> List<T>.toObservablePagedList(): Observable<PagedList<T>> {
val defaultConfig = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(size)
.setMaxSize(size + 2)
.setPrefetchDistance(1)
.build()
return RxPagedListBuilder(dataSourceFactory(this), defaultConfig)
.buildObservable()
}
/**
* src: https://gist.github.com/JoseAlcerreca/1e9ee05dcdd6a6a6fa1cbfc125559bba
*/
private fun <T> dataSourceFactory(itemList: List<T>): DataSource.Factory<Int, T> =
object : DataSource.Factory<Int, T>() {
override fun create(): DataSource<Int, T> =
ListDataSource(itemList)
}
/**
* src: https://gist.github.com/JoseAlcerreca/1e9ee05dcdd6a6a6fa1cbfc125559bba
*/
private class ListDataSource<T>(private val itemList: List<T>) : PositionalDataSource<T>() {
override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<T>) {
itemList.subList(params.startPosition, params.startPosition + params.loadSize)
.toMutableList()
}
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<T>) {
callback.onResult(itemList, 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment