https://kotlinlang.org logo
#flow
Title
# flow
m

Mohamed Ibrahim

10/07/2021, 1:38 PM
if I have this code
Copy code
private fun SearchScreenEvent.eventToUsecase(): Flow<SearchState> {
    return when (this) {
        is SearchClicked -> searchUsecase(this.query)
        is SearchQueryChanged ->
            flowOf(this.query)
                .debounce(5000)
                .flatMapConcat { searchUsecase(this.query) }
    }
}
why debounce is not working here
m

Matti MK

10/07/2021, 1:47 PM
Not quite sure, but I’m guessing you create a new
flow
on every
SearchQueryChanged
m

Mohamed Ibrahim

10/07/2021, 2:09 PM
this is true, back then with RxJava I was using
switchMap
with
publish
to resolve this, here is How I subscribe my events
Copy code
events
    .flatMapConcat { it.eventToUsecase() }
    .onEach { _states.value = it }
    .launchIn(viewModelScope)
I just want to control the text change events, so it debounce(someTime) and only take the latest emission
e

ephemient

10/07/2021, 4:24 PM
debounce on a single-element flow does nothing, you need it to live outside
👍 2
it would be easier if you had two separate flows to start with,
Copy code
merge(
    searchClicks,
    searchQueryChanges.debounce(5000L)
)
although you will have to grab the latest searchQuery when handling a searchClick, as the last SearchQueryChanged may be pending a debounce when this produces a SearchClicked
m

Mohamed Ibrahim

10/07/2021, 5:25 PM
Thank you that make since 👍
2 Views