If I’m using Paging 3 for my search list, I want t...
# android
i
If I’m using Paging 3 for my search list, I want to have a different Pager.flow each time I type something in SearchBox, right? Currently I’m doing this (collect from Paging flow into my SharedFlow):
Copy code
private var currentSearch: Job? = null
private val debounceDelayMs = 500L

private val _searchPagingFlow = MutableSharedFlow<PagingData<TaskModel>>()
override val searchPagingFlow: Flow<PagingData<TaskModel>> = _searchPagingFlow

override fun searchByText(text: String) {
    currentSearch?.cancel()
    currentSearch = ioThenMain({
        delay(debounceDelayMs)
        repository.searchTasks(text)
    }) { pagingFlow ->
        pagingFlow.collect {
            _searchPagingFlow.emit(it)
        }
    }
}
but this approach won’t save current search items, because I’m using SharedFlow. What can I do here to make it work properly?
j
What is
ioThenMain
here? I'm not sure how you're handling your jobs here with
ioThenMain
because I'm not aware of such function. Looks like it starts some coroutine outside of structured concurrency - which would be quite bad. Where is the scope for this job?
It seems you could send new search texts to a flow, and then use flatMapLatest on that flow to perform the search and produce the flow of results. This would automatically handle cancelling the collection of the previous results flow.
i
I renamed our internal function which launches a coroutine on Dispatchers.IO then passes result to Dispatchers.Main. It uses created scope with SupervisorJob. Thanks for the suggestion, I will try that
I ended up doing this and it’s working, but still it calls
repository.searchTasks(it)
every time I come back to this screen. Can it be because of
collectAsLazyPagingItems
?
Forgot to call
cachedIn(scope)
. Now it’s working perfectly. Thanks, man!
j
Cool! Glad it works for you. Although you should still consider fixing your
ioThenMain
function so it integrates better with structured concurrency so you avoid potential coroutine leaks
i
I would appreciate if you review our solution.
ioThenMain
is called
makeRequest
here basically we create our own scope with
SupervisorJob
and then launch our coroutines inside of it. The only problem might be with
CancellationException
suppression inside
makeRequest
, but it handled properly, imho