It there a way to limit the rate at which a flow e...
# coroutines
t
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
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
I think
debounce
does this in one step
n
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
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)
.