How can I make sure to start collecting to a `Muta...
# coroutines
m
How can I make sure to start collecting to a
MutableSharedFlow
before emitting something ?
Copy code
val mutableFlow = MutableSharedFlow<Int>()
      val sharedFlow = mutableFlow.asSharedFlow()

      // start listening to the sharedFlow
      launch {
        sharedFlow
            .collect {
              // by the time we start collecting, the first item is gone already
              // and nothing is received
              println("$it")
            }
      }
      // emit something 
      mutableFlow.emit(1)
Adding a delay before emitting works but doesn't sound great and I don't see a way to enforce a before-after relationship there
t
a simple
yield()
instead of delay might do the trick, but you can also collect the
.subscriptionCount
on your
mutableFlow
until it is
1
m
collect the 
.subscriptionCount
This will ultimately be called from different threads so that sounds dangerous
t
if you’ve collected 1 there, you can be sure someone started collecting, regardless of threads
if you want to be sure they also did not stop, that’s quite a bit broader of a requirement
m
It's a broadcast scenario where a collector will filter only a subset of all emitted items
Each collector also "controls" when the item start being emitted
But I want to make sure they don't miss any
t
today i learned 1
👍 1
🙏 1
j
launch(start = UNDISPATCHED) { .. }
🙏 2
👌 1
👍 1
the coroutine will eagerly start in the current stackframe until it hits a suspension point (in this case, the collect call)
b
passing
replay = 1
into MutableSharedFlow would also get you the println
m
@babel yea but
replay = 1
doesn't work anymore if there can be n emitted items as I don't know 'n' beforehand. Overall I like the
onSubscription()
solution. Looks like it was made especially for this use case
👍 1