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

Maciek

07/06/2020, 6:18 PM
I'm wondering how to structure the code inside the class where I need something like an interval from RxJava, that'll do heavy operation every 50ms. The problem is that I'd want the channel producer to execute heavy operation only when someone is collecting the flow. I don't want to waste resources. Is there some easy way to achieve it?
👀 1
d

Dominaezzz

07/06/2020, 6:22 PM
Are you going to have multiple collectors?
m

Maciek

07/06/2020, 6:22 PM
only one, but it can resubscribe multiple times
d

Dominaezzz

07/06/2020, 6:23 PM
You'll probably want a
SharedFlow
, which will let you pause production based on
subscriberCount
. It hasn't been released yet though.....
🙌 1
Since you have the guarantee of one collector. You can always just use
flow { /* loop and emit */ }
(Sans the channel)
m

Maciek

07/06/2020, 6:31 PM
do you mean like that? Can't wrap my head around how otherwise I could expose the flow as a field that is created inside a method
d

Dominaezzz

07/06/2020, 6:44 PM
Is the
initialize
method strictly necessary?
Just initialise the
flow
at construction and it won't run until there is a subscriber.
m

Maciek

07/06/2020, 7:14 PM
unfortunately it is, the snippet is simplified. For heavy operation, I need stuff from initialize method
d

Dominaezzz

07/06/2020, 7:17 PM
In that case, you could use a
CompletableDeferred
and
complete
it in the
initialize
method with heavy result. The you can consume the
CompletableDeferred
in the flow. This also means that if flow collectors will suspend until
initialize
is called.
3 Views