So it seems like a SharedFlow is a hot flow... but...
# coroutines
c
So it seems like a SharedFlow is a hot flow... but it doesn't require you to specify a scope. On the other hand, you can take a cold flow, and call the
shareIn
operator on it to get a hot flot but you need to provide a scope. Why can you have a SharedFlow with no scope, and a coldFlow.shareIn() requires a scope?
f
the hot flow needs to be collected so that its emissions can be shared. When you create a MutableSharedFlow, the fact or creating it doesn't require a scope, but collecting it does
c
oh. I was reading the docs and the docs made it seem like a SharedFlow is started/hot the moment it is created. let me re-read. i guess i missed something pretty fundamental here
f
are you talking about
val foo = MutableSharedFlow(/* ... */)
?
this is hot in the sense that you can push values to it and they will go through the flow regardless of collectors. If you have a buffer size of 1 for instance and drop oldest, new collectors will only receive the last emission and the other emissions will be dropped
j
When you convert a cold flow to a shared flow, you need a coroutine to collect the cold flow and send values to the shared flow, that's why you need a scope. A mutable shared flow is just an object to which you can send values, or from which you can get values. You'll have coroutines sending values to it, and coroutines getting values from it. All of those will need a scope.
☝️ 1
e
flow.shareIn(scope)
MutableSharedFlow().apply { scope.launch { flow.collect { emit(it) } } }
that's one coroutine dedicated to collecting the original flow and emitting items to the shared flow. but if you create your own mutable shared flow, you can emit to it from anywhere. the flow isn't scoped, the collector is