0

I'm getting some data from my database like this

Pager(PagingConfig(pageSize = PAGE_SIZE)) {
        songRepo.getSongs()
    }.flow.cachedIn(viewModelScope)

and I collect it in the UI using collectAsLazyPagingItems(), but whenever I navigate to another screen and I go back the data is clearing. Is there a solution to this or I should create my own pagination without Paging?

Unes
  • 312
  • 7
  • 12
  • Are you creating new Pager instance every time or do you store it in your ViewModel? – Jan Bína Sep 19 '22 at 12:40
  • No just one instance – Unes Sep 19 '22 at 13:25
  • How is your viewmodel created? – vitidev Sep 19 '22 at 18:43
  • with dagger hilt – Unes Sep 19 '22 at 20:50
  • Why do you need `viewModel.setSongs(songs)`? – vitidev Sep 19 '22 at 22:25
  • I don't use `LazyPagingItems` directly from `collectAsLazyPagingItems` I store it in the view model then I use it from there so I can avoid the data refreshing – Unes Sep 20 '22 at 05:41
  • `.cachedIn(viewModelScope)` avoid the data refreshing and this is enough if the view model is the same – vitidev Sep 20 '22 at 11:38
  • I used item element before `LazyPagingItems` items and that's the reason. This is a bug in the package issue's link https://issuetracker.google.com/issues/179397301 – Unes Sep 20 '22 at 11:56
  • from comments: "any item outside of the items from the paging library will cause the scroll position to be lost." - it is real reason, [temporary solution](https://issuetracker.google.com/issues/177245496#comment24) worked. Also `state.songs?.let` is unnecessary – vitidev Sep 20 '22 at 14:24

1 Answers1

-2

You will have to create a new instance of Pager every time you come back from a new screen.

Pager(PagingConfig(pageSize = PAGE_SIZE)) {
   songRepo.getSongs("albumId",false )
 }.flow.cachedIn(viewModelScope)
Ramesh Yankati
  • 1,197
  • 9
  • 13