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

zak.taccardi

10/24/2019, 10:21 PM
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

Farhan Khan

10/24/2019, 10:24 PM
z

zak.taccardi

10/24/2019, 10:26 PM
updated original message with my current solution
I guess
isActive
doesn’t matter because delay suspends
d

Dico

10/24/2019, 10:30 PM
What's wrong with using
flow
and
emit
?
z

zak.taccardi

10/24/2019, 10:33 PM
flow and emit is cleaner
o

octylFractal

10/24/2019, 10:42 PM
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

zak.taccardi

10/24/2019, 10:43 PM
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

octylFractal

10/24/2019, 10:46 PM
emit suspends, yes.
z

zak.taccardi

10/24/2019, 10:47 PM
Oh. I think I want to not poll again until my logic to check if I am in the correct state completes
o

octylFractal

10/24/2019, 10:47 PM
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

zak.taccardi

10/24/2019, 10:47 PM
As the whole flow is just one Coroutine I think it achieves that
l

louiscad

10/24/2019, 10:54 PM
I guess
isActive
doesn’t matter because delay suspends
No, it's because
delay
is cancellable.
👍 3
g

gildor

10/24/2019, 11:11 PM
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
6 Views