I've read that hot Flows do not terminate, unlike ...
# coroutines
m
I've read that hot Flows do not terminate, unlike BroadcastChannels. If I were to keep creating non-emitting stateflows and leave them unsubscribed, would these hot flows use up my cpu or memory, leading to possible resource outages? my guess is that it won't use cpu since it doesn't emit any signals, nor occupy memory since unused objects get GC-ed but Im not so sure
specific usage -> I'm using StateFlows to provide "the number of customers viewing the same product right now" using StateFlow's subscriptionCount api
e
within the same scope, yes you will use additional memory with each new stateflow
when the scope that you use to start a
.stateIn()
is cancelled, so is the hot flow, but as long as the scope is still running, the stateflow has a runnable coroutine referencing it
m
ohhh... I see so I would have to 1. create a scope for each hot flow that I create, 2. start the flows in independent scope and 3. cancel the scope of the sharedflows I want to end in order to prevent memory leak?
idk if it's a promising solution (definitly not feeling it 🥲 ) maybe I should turn to other means...
e
you can emulate
onInactive
with
subscriptionCount
, as the documentation itself has an example of
although if you're using that to cancel scope I feel like there's potential race issues
m
you can emulate 
onInactive
 with 
subscriptionCount
, as the documentation itself has an example of
I did emulate onInactive in the way you said but wasn't able to find any other way to stop the hot flows there (other than canceling independent scopes) 😿
thanks a lot anyway for your help!! mucho appreciated <3
j
It should be noted that there wouldn't be any [hidden] coroutine launched when using
MutableStateFlow
or
MutableSharedFlow
. The coroutines @ephemient is mentioning are only launched if you're "converting" a "regular" cold flow into a shared/state flow by using `stateIn()`/`shareIn()` (which do require a scope). This is because those operators start a coroutine that collects the initial cold flow and emit elements to subscribers. Using the mutable variants of those flows is actually pretty cheap: it's just a handle to which you can manually emit stuff, and collectors of these flows would get those emissions (a bit like a channel). Technically these mutable hot flows don't consume any CPU by themselves. However, the
MutableSharedFlow
could occupy a bit of memory depending on the buffer size (replay + extra).
e
creating your own Mutable*Flow doesn't create any background coroutines, yep. but handling your own publishing of updates to those flows leaves you in a similar position
👍 1
j
Yes, but that's not "hidden" anymore behind the library functions, so I thought it was kind of easier to count because it's other code that the developer writes