I'm wondering how to structure the code inside the...
# coroutines
m
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
Are you going to have multiple collectors?
m
only one, but it can resubscribe multiple times
d
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
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
Is the
initialize
method strictly necessary?
Just initialise the
flow
at construction and it won't run until there is a subscriber.
m
unfortunately it is, the snippet is simplified. For heavy operation, I need stuff from initialize method
d
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.