https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

tseisel

07/26/2022, 6:52 PM
It there a way to limit the rate at which a flow emits elements? My use case it to avoid running costly operations too often. For example, given the following source flow:
Copy code
val source = flow {
  emit("A")
  delay(100)
  emit("B")
  delay(50)
  emit("C")
  emit("D")
}
when applied a constraint of "max 1 element each 100ms", it should emit: • "A" at t = 0ms • "B" at t = 100ms • "D" at t = 200ms
n

Nick Allen

07/26/2022, 7:42 PM
Try:
Copy code
source
    .conflate()
    .transform {
        emit(it)
        delay(100)
    }
Conflate will keep track of the most recently emitted value during the
delay(100)
from the previous value.
r

rnett

07/26/2022, 8:12 PM
I think
debounce
does this in one step
n

Nick Allen

07/26/2022, 11:42 PM
Debounce delays items and drops them if a new one is detected. So
source.debounce(100)
would maybe give "A" at 100ms and would emit "D" at 250ms.
t

tseisel

07/27/2022, 10:19 AM
Many thanks @Nick Allen for your answer, it perfectly fits what I was looking for! I've been searching for an equivalent of
throttleLatest
Rx operator for so long that I couldn't imagine it would be so simple 😵 The best part with your code is that we can also get
throttleFirst
by replacing
conflate()
with
buffer(0, BufferOverflow.DROP_LATEST)
.
4 Views