https://kotlinlang.org logo
Title
d

diesieben07

08/25/2019, 6:42 PM
Am I correct in that the only difference between
flow { }
and
channelFlow { }
is that the latter is "threadsafe", meaning you can switch dispatcher inside the suspending block? Or is there something else?
🇳🇴 2
o

octylFractal

08/25/2019, 6:56 PM
back pressure also differs, since there is a channel between the sender/emitter and consumer
d

diesieben07

08/25/2019, 6:58 PM
Okay, what does that mean exactly? I understand the concept of backpressure, but how do the two differ in this regard?
a

Adam Powell

08/25/2019, 7:12 PM
It means that send returns when the value handoff is complete, contrasted with emit that returns after the downstream collector is done processing it
5
d

diesieben07

08/25/2019, 7:14 PM
I see. So it would depend on what kind of channel you have "in between", right? If it's a zero-capacity one you effectively have the same as with
emit
, otherwise you can buffer N elements before you need to wait for the collector.
o

octylFractal

08/25/2019, 7:18 PM
yes, and by default it buffers, but you can use
buffer
to change that
2
d

diesieben07

08/25/2019, 7:18 PM
Thanks to both of you, that clears it up!
z

Zach Klippenstein (he/him) [MOD]

08/25/2019, 7:48 PM
If it’s a zero-capacity one you effectively have the same as with
emit
Not quite –
offer
still returns as soon as the handoff is complete, which, depending on which dispatcher the downstream is running on, may be before the downstream actually finishes processing that item.
d

diesieben07

08/25/2019, 7:52 PM
So say the downstream is doing some long-running operation after receiving each value. With
emit
upstream would wait for that operation, with channels it would compute the next element, which would then have to wait for downstream (for the next handoff). Right?
z

Zach Klippenstein (he/him) [MOD]

08/25/2019, 7:53 PM
exactly
1
d

diesieben07

08/25/2019, 7:54 PM
Thank you
z

Zach Klippenstein (he/him) [MOD]

08/25/2019, 7:55 PM
but relying on those semantics can make for brittle code – e.g. nothing’s stopping a downstream consumer from putting a channel in the mix. if you actually need synchronization, and not just backpressure, better to synchronize explicitly
d

diesieben07

08/25/2019, 7:55 PM
Yes, obviously. I was just trying to understand the difference here