Skip to content

Instantly share code, notes, and snippets.

@danielgomezrico
Last active October 9, 2019 13:38
Show Gist options
  • Save danielgomezrico/cbd98365a840a93c4e6a04e25b2b1671 to your computer and use it in GitHub Desktop.
Save danielgomezrico/cbd98365a840a93c4e6a04e25b2b1671 to your computer and use it in GitHub Desktop.
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