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

Patrick Steiger

03/05/2023, 11:55 PM
Why is
subscriptionCount
a property of
MutableSharedFlow
instead of
SharedFlow
?
e

elizarov

03/06/2023, 8:21 AM
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

Patrick Steiger

03/06/2023, 4:02 PM
@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

elizarov

03/06/2023, 4:26 PM
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

Patrick Steiger

03/06/2023, 4:52 PM
Ok, creating my own sharing operator makes sense! Thanks @elizarov
12 Views