baxter
09/19/2024, 1:22 AMcallbackFlow
shareable, without requiring a CoroutineScope
(as required inside the shareIn()
extension)?baxter
09/19/2024, 1:23 AMJoffrey
09/19/2024, 2:13 AMshareIn
operator needs a scope because it needs to start a coroutine that will collect your cold flow and broadcast the values to subscribers. This coroutine needs a scope to runbaxter
09/19/2024, 2:57 AMMutableSharedFlow
(which doesn't need a scope to be created), but that can keep track of subscribers and unregisters the callback.baxter
09/19/2024, 2:58 AMproduce()
, but that might not handle shutting down the callback if no collectors are subscribed to the flow I can create from it.Zach Klippenstein (he/him) [MOD]
09/19/2024, 4:03 AMbaxter
09/19/2024, 4:07 AMbaxter
09/19/2024, 4:08 AMbaxter
09/19/2024, 4:09 AMbaxter
09/19/2024, 4:19 AMonCompletion
to track it instead. This might be the best approach.baxter
09/19/2024, 5:23 AMshareIn()
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.baxter
09/19/2024, 5:26 AMSharedFlow
from a callback without the need for callbackFlow {}.shareIn()
or the use of any coroutine scopes (other than when you collect on it).baxter
09/20/2024, 11:14 PMChannelCoroutine
that was somehow tied the number of subscribers of the flow.
I'll admit whatever madness I was chasing is lost in the past now.