What would be the idiomatic way to emit a `Flow&lt...
# coroutines
z
What would be the idiomatic way to emit a
Flow<Unit>
every 40 milliseconds? old solution:
Copy code
channelFlow<Unit> {
  while (isActive) {
    delay(40)
    send(Unit)
  }
}
new, better solution:
Copy code
flow {
    while (true) {
        delay(40)
        emit(Unit)
    }
}
f
z
updated original message with my current solution
I guess
isActive
doesn’t matter because delay suspends
d
What's wrong with using
flow
and
emit
?
z
flow and emit is cleaner
o
issue with flow & emit is that it does not account for the time spent in emit, so the question is do you want fixed rate or fixed delay. the former is better for fixed rate, latter for fixed delay, though you would probably need more code for a perfect fixed rate emission
☝️ 1
😲 1
z
I'm just trying to emulate
Oberservable.timer(..)
I'm trying to poll every 40ms to check some state, and once I have hit the correct state, terminate the flow (which I am doing via
filter { isInCorrectState}.first()
emit(..)
suspends though right?
o
emit suspends, yes.
z
Oh. I think I want to not poll again until my logic to check if I am in the correct state completes
o
probably if you're polling, fixed delay is fine, and you can use flow/emit. reason being that you want to wait 40ms after the last result, regardless of how long it takes.
👍 1
z
As the whole flow is just one Coroutine I think it achieves that
l
I guess
isActive
doesn’t matter because delay suspends
No, it's because
delay
is cancellable.
👍 3
g
Version with channel is less efficient and you just don't need it. Use flow, not channel flow in this case, you can have exactly same semantics, if you want. Channel flow is needed if you want to emit from different threads or from non-suspend context (like if you write flow adapter for some callback)
👍 1
1