1

There is query and two filters. When set search filter and query is not empty, need to one flow. When set checked filter need to other flow.

According debug, onClickSearchFilter or onClickCheckedFilter calls with query or filter changed - return new flow. But in UI no changes, collector dont work second time.

  1. How to switch flow based on condition?
  2. When I debugging with breakpoints in flows, app crash every time A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x14 in tid 23174 (JDWP), pid 23167 . Rebuild, clear cache, reload device - dont' help.
repeatOnStarted(viewModel.itemsFlow) {
    // it doesn't work when flow is switched
    pagingAdapter.submitData(it)
}
val itemsFlow = queryFlow
    .debounce(1000)
    .combine(filterFlow) { query, filter ->
        when (filter) {
            R.id.search_result_chip -> onClickSearchFilter(query)
            R.id.checked_chip -> onClickCheckedFilter()
            else -> throw Exception("")
        }
    }.flatMapMerge { // in order to switch from Flow<Flow<*>> to Flow<*>
        it
    }

private fun onClickSearchFilter(query: String): Flow<PagingData<ItemEntity>> {
    return if (query.length < 2)
        emptyFlow()
    else Pager(BasePagingSource.getConfig()) {
        SearchPagingSource(query, client)
    }.flow.cachedIn(viewModelScope)
}

private fun onClickCheckedFilter(): Flow<PagingData<ItemEntity>> {
    return Pager(
        config = BasePagingSource.getConfig(),
        remoteMediator = RemoteMediator(checkedIds, cacheDatabase, client)
    ) {
        cacheDatabase.itemDao.getPagingSource(type, checkedIds)
    }.flow
}
Viewed
  • 1,159
  • 3
  • 16
  • 43
  • 1
    Not positive, but try replacing `flatMapMerge` with `flatMapLatest`. That might not resolve your issue, but you need to make that change regardless. Otherwise, your previous queries and filters will still be running concurrently with the new ones and merged together (interleaved). You need to be dropping/cancelling any previous queries/filters as new ones arrive. – Tenfour04 Jan 19 '23 at 14:48
  • @Tenfour04 it works with `flatMapLatest` for `itemsFlow` and `collectLatest` on fragment side – Viewed Jan 19 '23 at 16:12

0 Answers0