is there any throttle operator for flow ?
# coroutines
m
is there any throttle operator for flow ?
m
no. debounce basically filter values based on timeout, but emits the last ones. throthle filter values based on timeout, but emits first ones
o
ah, I'm not super familiar with rx so didn't understand. sounds like https://github.com/Kotlin/kotlinx.coroutines/issues/1446
m
imagine some network call on a search functionality. basically, you filter out quickly emited items, and only get the last one based on some time
thats debounce
now imagine for instance, a button trigger a network call, and you want to filter out double quick emissions. you cannot use debounce because then the click will be delayed, you need throtle
s
There is none, as far as i know. But writing one yourself should not be that hard.
m
yes, im working on that right now
1
t
I need the same operators, especially
throttleLatest
. I started writing code to submit a PR in coroutines library
k
Maybe I'm not following correctly, but will this suffice? https://github.com/Kotlin/kotlinx.coroutines/pull/1798
m
yes, it seems so. is it in latest version yet ?
k
nope. I'm hoping to finish up the PR this weekend. Has been more complicated than anticipated
however, for the time being, you can emulate 99% of the functionality (except for some edge cases) with this
Copy code
/**
 * Consume this [Flow] using a channelFlow with no buffer. Elements emitted from [this] flow
 * are offered to the underlying [channelFlow]. If the consumer is not currently suspended and 
 * waiting for the next element, the element is dropped. 
 * 
 * @return a flow that only emits elements when the downstream [Flow.collect] is waiting for the next element
 */
fun <T> Flow<T>.drop(): Flow<T> = channelFlow {
    collect { offer(it) }
}.buffer(capacity = 0)
m
ok. will try. thanks
d
Did you take a look at
conflate()
? It is not exactly the same behavior but maybe it could help
1790 Views