Debouncing my Flow isn't working as I expected. Fe...
# getting-started
c
Debouncing my Flow isn't working as I expected. Feel like I'm missing something basic here:
Copy code
13:50:11.748  E  emitting 13
13:50:11.883  E  emitting 493
13:50:13.755  E  dispatching 493
13:50:14.129  E  emitting 493
13:50:14.272  E  emitting 493
13:50:14.345  E  emitting 493
13:50:14.732  E  emitting 493
13:50:15.012  E  emitting 493
13:50:15.211  E  emitting 493
I would expect two dispatches in my logs. Code in thread
Copy code
viewModelScope.launch {
    Log.e("LOG", "emitting ${items.flatMap { it.items }.size}")
    myStateFlow.emit(items)
}
Copy code
viewModelScope.launch {
    myStateFlow.debounce(2_000).collectLatest { dispatchItems(it) }
}
Copy code
fun dispatchItems(items: Set<Items<Person>>) {
        Log.e("LOG", "dispatching ${items.flatMap { it.items }.size}")
...
e
why? that all seems expected as per the docs
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/debounce.html
Note that the resulting flow does not emit anything as long as the original flow emits items faster than every
timeoutMillis
milliseconds.
looks like the only gap in your timings longer than that is where the dispatch happened
c
hm. i guess something isn't clicking yet. it doesn't seem weird to you that there's no second dispatch about 2 seconds after the first (and only) dispatch?
Changed it to a SharedFlow and now it seems to be working as I expected?
c
What did you expect?
c
Pretty much just thinking there'd be one last dispatch event like so 135011.748 E emitting 13 135011.883 E emitting 493 135013.755 E dispatching 493 135014.129 E emitting 493 135014.272 E emitting 493 135014.345 E emitting 493 135014.732 E emitting 493 135015.012 E emitting 493 135015.211 E emitting 493 135015.211 E dispatching 493
e
how would it know not to wait for events after the last one?
c
i guess i dont know, but i could have sworn i was using debounce in rxjava this way. but maybe i was using rx wrong. dang. i wonder the best way to get this done is then lol