Kotlin / kotlinx.coroutines

Library support for Kotlin coroutines
Apache License 2.0
12.86k stars 1.83k forks source link

Add a .throttle(Duration) Flow extension that prevents short burst of emission in a time frame #3845

Open NinoDLC opened 11 months ago

NinoDLC commented 11 months ago

Use case

I read BLE characteristics and send them throught a Flow for the rest of my application to act on it. The BLE characteristics are based on real world events (think of something like a rowing machine). Sometimes, the Flow would emit TONS of values in a very short time frame, sometimes it wouldn't emit for several seconds. I want to limit the "rate" of emission to a maximum of, say, 10 / second. Any higher value is putting the code to unnecessary stress.

Currently, the 2 available APIs won't help me :

The Shape of the API

flow {
    repeat(10) {
        emit(it)
        delay(110)
    }
    delay(300)
    emit(42)
}.throttle(200)

produces the following emissions
0, 2, 4, 6, 8, 10, 42

Prior Art

Even if it's not really and argument, Rx has it and it's convenient. https://rxmarbles.com/#throttle

dkhalanskyjb commented 10 months ago

See also https://github.com/Kotlin/kotlinx.coroutines/issues/460

hoc081098 commented 10 months ago

Currently, you can use my extension https://github.com/hoc081098/FlowExt