Why does the following ```val shared = MutableSharedFlow<Int>() merge( shared.onSubscriptio...
d
Why does the following
Copy code
val shared = MutableSharedFlow<Int>()
merge(
  shared.onSubscription { shared.emit(3) },
  flowOf(100,200,300),
).collect {
  println("$it")
}
never prints
3
, only
100 200 300
? And is there a way to setup this so that I have some point where it is safe to post to
shared
to guarantee delivery to
collect
?
a
using
Copy code
shared.onSubscription { emit(3) }
instead of
Copy code
shared.onSubscription { shared.emit(3) }
actually works as expected. I think your problem is that
onSubscription
doesn't modify
shared
but returns a new
SharedFlow
instead. so
shared.emit(3)
emits
3
to a flow that is actually never subscribed?
d
Yeah, that works, but I need to emit to
shared
, because it can have other subscribers. This sample is a minimal reporduction of the issue I have on a larger scale.
so
shared.emit(3)
emits
3
to a flow that is actually never subscribed?
That's not the case, because it's passed to
merge
and merge will subscribe to it. Nevertheless I'm interested to know why doesn't this work as it is :)
n
I guess that when onSubscription { } is invoked, the shared flow is not yet in a ‘subscribed’ state, so emissions are dropped. Adding replay = 1 should work, but proper solution is to just do
emit(3)
. Instead of calling onSubscription for every subscriber, you should save it somewhere:
val shared2 = shared.onSubscription { emit(…) }
and have subscribers subscribe to shared2