Paging 3.0 list with new params in Kotlin
Asked Answered
L

1

5

I have the following code:

   val history: Flow<PagingData<Any>> = Pager(PagingConfig(pageSize = 10)) {
    PaginationBaseDataSource(apiService)
}.flow
    .cachedIn(viewModelScope)

This currently is displaying a list of items without any additional params. This works Ok... But now I wish to query this list based in certain params that the user can change in frontend, let´s say I wish to add the parameter 3 as a query.

   val history: Flow<PagingData<Any>> = Pager(PagingConfig(pageSize = 10)) {
    PaginationBaseDataSource(apiService, 3)
}.flow
    .cachedIn(viewModelScope)

The question is... How can I set this query parameters on the fly? Let´s say the user instead of 3, used 6 and then 9. How can I achieve this?

Thank you very much

Lanoralanose answered 5/11, 2020 at 6:34 Comment(0)
L
3

You'll want to emit a new PagingData anytime one of your args changes. A flow-style way of achieving this might look like:

val queryFlow = MutableStateFlow(value = 3)
val pagingDataFlow = queryFlow.flatMapLatest { query ->
    Pager(...) { MyPagingSource(query) }.flow.cachedIn(viewModelScope)
}
Larch answered 5/11, 2020 at 9:9 Comment(3)
its working but how to prevent list refreshing on coming back to fragment? seems cachedIn not work by this solution.Ansley
You cannot fully prevent it because that would require preventing lifecycle from destroying your fragment. Make sure to implement PagingSource.getRefreshKey to allow fragment to resume from where it was last viewed. DiffUtil will help transition smoothly to the user in this case so there shouldnt be any "refreshing" effectLarch
items of my list changing on refresh some times. can you please help me to solve this problem: https://mcmap.net/q/667743/-android-paging-3-library-how-to-change-list-with-new-param/10109704 it about paging 3.Ansley

© 2022 - 2024 — McMap. All rights reserved.