Unable to refresh recyclerView with pagination

谁都会走 提交于 2020-08-10 12:25:25

问题


I have a RecyclerView that gets filled with paginated data.

I need to be able to refresh it via SwipeRefreshLayout, but so far, I am unable to do so.

I have tried plenty references that does similar to this, but without any success. Also, for letting you guys know, When I do refresh, the data gets retrieved correctly, but it is not being displayed on the recyclerView...

Also, when I move from that destination to another via Navigation and then, I hit back, it gets updated. I am not sure what I am missing or what I am doing wrong.

ViewModel:

class ActivityViewModel : ViewModel() {
    var itemDataSourceFactory = OperationsDataSourceFactory()
        private set
    val livePagedList: LiveData<PagedList<Result<Operation?>>>

    init {
        val config = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setInitialLoadSizeHint(10)
            .setPageSize(10)
            .build()

        livePagedList = LivePagedListBuilder(itemDataSourceFactory, config).build()
    }

    fun refresh() {
        itemDataSourceFactory.dataSourceLiveData.value?.endCursor = null
        itemDataSourceFactory.refresh()
    }
}

DataSourceFactory:

class OperationsDataSourceFactory :
    DataSource.Factory<String, Result<Operation?>>() {
    val dataSourceLiveData = MutableLiveData<OperationsDataSource>()
    lateinit var dataSource: OperationsDataSource
    override fun create(): DataSource<String, Result<Operation?>> {
        dataSource = OperationsDataSource()
        dataSourceLiveData.postValue(dataSource)
        return dataSource
    }

    fun refresh(){
        dataSourceLiveData.value?.invalidate()
    }
}

And, on the Fragment, I have something like this:

private fun initView() {
    binding.swipeToRefresh.setOnRefreshListener {
        itemViewModel.refresh()
    }
    getData() //observables with adapter.submitList(list)
}

回答1:


Ok, after a really long research, might not be the best solution, but developers use this too. We need to "invalidate" the layoutManager and adapter.

swipeToRefresh.setOnRefreshListener {
    operationsRecycler.apply {    
    layoutManager = null
    adapter = null
    layoutManager = LinearLayoutManager(
                        requireContext(),
                            LinearLayoutManager.VERTICAL,
                            false
                        )
    adapter = myAdapter
}


来源:https://stackoverflow.com/questions/62840390/unable-to-refresh-recyclerview-with-pagination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!