kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Add throttleFirst Flow operator

Open fluidsonic opened this issue 5 years ago • 4 comments

We have no operator that prevents subsequent emissions for a certain time after an emission. In RxJava there is throttleFirst for that.

flow {
    repeat(10) {
        emit(it)
        delay(101)
    }
}
    .throttleFirst(500)
    .collect {
        println(it)
    }

The example above should print 0 and 5. Both should be emitted without any added delay.

One use-case is button clicks where (accidental) repeated clicks should be filtered. If I click a button twice accidentally, only the first click event would make it downstream and the second click be ignored because it came in too fast after the first one.

debounce(500) is not suitable because it a) delays the emission of the first value by at least 500ms and b) delays the emission of any value until the user stops clicking for at least 500ms.

sample(500) is not suitable because it a) delays the emission of the first value by 500ms and b) emits nothing if the Flow is closed within 500ms after collection has started.

The related throttleLatest was mentioned in #1107 but no reason was given why it nor it's siblings have made it into Flow so far.

fluidsonic avatar Apr 20 '20 18:04 fluidsonic

@fluidsonic If I'm not wrong. The above throttleLatest example should print 0, 4. The operator you want seems being called throttleFirst. Plese see https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#throttlefirst

jxdabc avatar May 07 '20 09:05 jxdabc

@jxdabc you're right, throttleFirst is more appropriate for solving the problem. I'll update the issue.

fluidsonic avatar May 07 '20 10:05 fluidsonic

Duplicate of https://github.com/Kotlin/kotlinx.coroutines/issues/1446

davidmigloz avatar Dec 07 '21 18:12 davidmigloz

please check my lib https://github.com/hoc081098/FlowExt

  • https://github.com/hoc081098/FlowExt
  • https://hoc081098.github.io/FlowExt/docs/latest/-flow-ext/com.hoc081098.flowext/throttle-time.html

hoc081098 avatar Mar 24 '22 18:03 hoc081098