Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"restore scroll position in android Paging adapter when user go to another fragment or activity from adapter" problem

How can ı restore paging adapter item state when ı move to another fragment? I tried article below but it didnt work. https://medium.com/@florina.muntenescu

private fun loadData() {
        viewModel.apply {
            lifecycleScope.launch{
                viewModel.getMorePopularMovies().collectLatest { pagingData ->
                    dataAdapter.submitData(viewLifecycleOwner.lifecycle, pagingData)

                }
            }
        }

    }

fun getMorePopularMovies() = Pager(
        PagingConfig(pageSize = 3)
) {
    VerticalMoviePagingSource(api, "Popular")
}.flow
like image 772
Ahmet Faruk Çuha Avatar asked Sep 20 '25 11:09

Ahmet Faruk Çuha


1 Answers

Try adding .cachedIn(viewModelScope) in your viewModel code. For your case you will get:

  fun getMorePopularMovies() = Pager(
        PagingConfig(pageSize = 3)
) {
    VerticalMoviePagingSource(api, "Popular")
}.flow.cachedIn(viewModelScope)

And try adding in your fragment:

adapter.stateRestorationPolicy =
        RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

If it doesn't work then there is another problem in your code, I guess.

like image 150
SimpleX Avatar answered Sep 23 '25 03:09

SimpleX