0

I have 2 screens: ScreenA() and ScreenB()

@Composable 
fun ScreenA(
   val viewModel: ScreenAViewModel = hiltViewModel()
){
   val data = remember{
         viewModel.pagingData()
     }.collectAsLazyPagingItems()

   LazyColumn(){
     items(data){
       //show individual data.
    }
 }
}

@Composable
fun ScreenB(){
//Screen B code
}

@HiltViewModel
class ScreenAViewModel @Inject
constructor(
val myrepo: MyRepository
): ViewModel(){
  fun pagingData() = myrepo.pagingData().cachedIn(viewModelScope)
}

class MyRepository @Inject constructor(){

  fun pagingData() = Pager(
       config = PagingConfig(10),
      pagingSourceFactory = {
             MyPagingSourceFactory()
       }
    ).flow

}

My start destination is ScreenA.

The problem is after a successful loading of data in ScreenA, I navigate to screenB and then turn of my internet connection. On popping ScreenB from the navStack, the previously loaded data is lost. On logging the states of paging data, I found that paging data is triggering a refresh on re-navigation and I think that is causing the data to be reinvalidated and as refresh is unsuccessful, new data are not loaded.

How to stop refresh on renavigation or even better, how to save the state of previously loaded data on navigation?

Diken Mhrz
  • 327
  • 2
  • 14

1 Answers1

0

keep data cache in viewModel scope. in my case it solved the poblem.

Pager(PagingConfig(pageSize =  30)) {
            AllNewsSource(newsRepository)
        }.flow.cachedIn(viewModelScope)
Arvin Rezaei
  • 818
  • 10
  • 25
  • am I not doing the same thing? – Diken Mhrz Oct 10 '22 at 07:29
  • 1
    i guess you are making new Pager Everytime composition is happened in page A . pagingData() everytime returns a new instance , keep the instance in viewModel, if didn't worked , try to use in rememberSavable – Arvin Rezaei Oct 10 '22 at 11:35