How could you create `sharedFlow` builder with the...
# coroutines
h
How could you create
sharedFlow
builder with the same signature like the cold
flow
builder:
fun<T> sharedFlow(block: suspend FlowCollector<T>): SharedFlow<T>
? It always requires a
CoroutineScope
...
e
what would it mean to create a shared flow without a scope? if it didn't, and you ran
Copy code
sharedFlow.collect() // in scope 1
sharedFlow.collect() // in scope 2 in parallel
then cancelled one of the scopes, in what scope should the single shared producer be running?
h
I don't understand your problem. Currently, you could do this:
Copy code
fun<T> sharedFlow(block: MutableSharedFlow<T>.() -> Unit): SharedFlow<T> = MutableSharedFlow<Int>().apply(block)

val sf = sharedFlow {
    tryEmit(42)
}
But would like to use
emit
(and FlowCollector) instead.
e
if
sf
were a plain
flow
, then
tryEmit
runs as a child within the scope of each collector
but since it's a
SharedFlow
, there should be a single coroutine running
tryEmit
regardless of how many parallel collectors there are
how should that work? if you pick the first collector, what do you do when it's cancelled?
h
Oh, after canceling the first collector, the SharedFlow should still emit the values, no matter how many collectors are actually subscribing.
e
so… how would that even work? you can't re-parent the running coroutine
h
I want to have one SharedFlow acting as producer and multiple consumer... But yeah, after reading it again, the producer needs its own scope to run independently.
o
@hfhbd you looking for produce { } ?
h
Not really, produce returns a channel, I want to get a
SharedFlow
.
o
Why do you want to get a
SharedFlow
?
h
Because I want to migrate from BroadcastChannel to ShareFlow.
o
What is your code trying to do?
h
It listens a hot event source and should broadcast these values to each subscriber, if present.
o
Yes, you can do produce { ... }.receiveAsFlow()
h
Yeah, but why? I am currently using
broadcast
and want to migrate it to SharedFlow. Why should I use
produce
?
o
Why do you want to migrate to SharedFlow if produce does what you want? I could help you better if you could share your code piece🙂