Interesting... So I took a dive into the
shareIn()
code to figure out why it really needs a
CoroutineScope
and it makes sense when converting a cold flow to a hot flow, as they collect the
subscriptionCount
state flow and map the upstream flow to the downstream flow based on the differing subscription events, or
SharingStarted
passed. However, it doesn't make sense if you want to broadcast the results of a callback to multiple collectors by doing
callbackFlow {}.shareIn()
.
The "upstream flow" is actually a
producer
, which accepts the events from the callback itself. So really, the upstream flow is the callback emitting the events. Say we are using
trySendBlocking()
to emit the events on the callbackFlow, then we can just do something like:
if (!sharedFlow.tryEmit(value)) { runBlocking { sharedFlow.emit(value) } }
on the callback event emit instead.
Once we have that, we can just do a
transformLatest
off the
subscriptionCount
and the
SharingStarted
value passed, pass that as a wrapped shared flow, and then we can have a "shared" callbackFlow.