Why is `subscriptionCount` a property of `MutableS...
# coroutines
p
Why is
subscriptionCount
a property of
MutableSharedFlow
instead of
SharedFlow
?
e
SharedFlow
is a “consumer interface” while a
MutableSharedFlow
is the corresponding “producer interface”. The design assumes that it is only in producer’s right to know the subscription count, so that it can adjust producing strategy appropriately.
p
@elizarov ok, that makes sense, conceptually. Still, it makes it awkward to implement logic that depend on knowing “how many subscribers are there in the SharedFlow” when production of values is not coming from a MutableSharedFlow, and instead comes from a cold flow turned hot (e.g shareIn or stateIn). E.g given a StateFlow that holds UI state, start some other authenticator coroutine when there are subscribers to it, or cancel them when there aren’t. This use case forces the ceremony of using a MutableStateFlow to back the StateFlow when it could more simply be represented as a cold flow turned hot. Note that in the example, the values produced into the StateFlow does not necessarily depend on the associated Authenticator coroutine to be launched when StateFlow is being subscribed to, so making it a side effect of the upstream cold flow doesn’t feel right.
e
If you are writing such a logic, then you should not be using
shareIn
and
stateIn
. It is them who manage sharing in this case. If you want to manage it, instead, then create your own instance of
MutableShared/StateFlow
like
share/stateIn
implementation does.
p
Ok, creating my own sharing operator makes sense! Thanks @elizarov