I implemented endless scroll for my list using Android Paging library. I download data from the API in portions depending of pages. My app allow user to filter items by adding some parameters into API query. After enabling filtering I like to change parameters
field into PageKeyedDataSource
instance and reset loader (i want to set page to 1 and call loadInitial method in it)
DataSource(private var initialData: List<Data>, var parameters: HashMap<String, String>) : PageKeyedDataSource<Int, Data>() {
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Data>) {
callback.onResult(initialData, null, 2)
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Data>) {
val page = params.key
parameters[PAGE] = page.toString()
val request = ApiRequest()
request.setOnDataObtainListener {
callback.onResult(it,page.inc())
}
request.getData(parameters)
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Data>) {
}
fun reset(initialData: List<Data>, parameters: HashMap<String, String>) {
this.parameters = parameters
this.initialData = initialData
invalidate()
}
}
my view model class
ViewModelData : ViewModel() {
private var dataList: LiveData<PagedList<Data>>? = null
private var dataSourceFactory: DataSourceFactory? = null
fun loadData(initialData: List<Data>, parameters: HashMap<String, String>): LiveData<PagedList<Data>> {
if (newsDataList == null) {
dataSourceFactory = DataSourceFactory(initialData, parameters)
val config = PagedList.Config.Builder()
.setPageSize(10)
.setInitialLoadSizeHint(10)
.setEnablePlaceholders(false)
.build()
if (dataSourceFactory != null) {
dataList = LivePagedListBuilder<Int, Data>(dataSourceFactory!!, config)
.setInitialLoadKey(1)
.build()
}
}
return dataList as LiveData<PagedList<Data>>
}
fun reset(initialData: List<Data>,parameters: HashMap<String, String>) {
dataSourceFactory?.dataSourceLiveData?.value?.reset(initialData,parameters)
}}
I Guess invalidate
will work but im unable to clear PagedList from adapter.