Paging 3 RemoteMediator and SavedStateHandle

571 Views Asked by At

I'm using the RemoteMediator in an app to load page keyed data. Everything works fine, except when after process death, the data is refreshed.

My current implementation is :

val results = savedStateHandle.get<String>("query").flatMapLatest { query ->
    repository.getPager(
        query = query,
    )
}.cachedIn(viewModelScope)

I do know about the initialize() function of RemoteMediator, but how do I tie it in with process death?

1

There are 1 best solutions below

0
dlam On

As you found out, .cachedIn just operates in memory, so it won't survive process death. You cannot rely on Paging's internal cache of items in memory for this, you need to cache the loaded items on disk.

I would recommend using something like Room or some dedicated persistence layer that is actually built to handle large lists of arbitrary data classes.

I would not recommend to try to serialize and stash the entire list of data into SavedState as this could become prohibitively expensive quite quickly.

For your other point on RemoteMediator - it is just a "dumb" callback which has no influence on what Paging actually loads or displays. It's simply a way for your to write custom logic which is triggered during edge-case conditions in Paging. You probably only want this if you are already using a layered approach and trying to skip remote REFRESH. If that is your case, the RemoteMediator.intiailize function is guaranteed to complete before Paging starts loading, which means you can check whether you are coming from SavedState and there is already cached data, and if so, you can skip remote REFRESH by returning InitializeAction.SKIP_INITIAL_REFRESH.