Paging library, reset PageKeyedDataSource
Asked Answered
D

1

6

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.

Dustindustman answered 27/9, 2019 at 6:23 Comment(1)
i have same problem too.. have you found the solution?Pussy
C
0

this func will clear current list on a screen

  adapter.submitList(null)

adapter - your adapter for RecyclerView

and this clear a pagingDataSource

pagedList.value.dataSource.invalidate()

then we could load a new list

Chiccory answered 6/9, 2023 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.