https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

mbonnin

05/07/2021, 3:07 PM
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

Tijl

05/07/2021, 3:14 PM
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

mbonnin

05/07/2021, 3:18 PM
collect the 
.subscriptionCount
This will ultimately be called from different threads so that sounds dangerous
t

Tijl

05/07/2021, 3:25 PM
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

mbonnin

05/07/2021, 3:27 PM
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

Tijl

05/07/2021, 3:38 PM
today i learned 1
👍 1
🙏 1
j

jw

05/07/2021, 3:38 PM
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

babel

05/07/2021, 9:29 PM
passing
replay = 1
into MutableSharedFlow would also get you the println
m

mbonnin

05/07/2021, 9:36 PM
@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
3 Views