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

Dominaezzz

07/10/2021, 1:48 PM
Why doesn't this deadlock?
Copy code
val stream = MutableSharedFlow<Unit>()
val unused = stream.buffer(Channel.RENDEZVOUS).produceIn(GlobalScope)
stream.emit(Unit)
m

mbonnin

07/10/2021, 1:51 PM
I think
MutableSharedFlow
will drop events if there are no subscribers
💯 2
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/index.html
Copy code
in the absence of subscribers emitter never suspends despite BufferOverflow.SUSPEND option and BufferOverflow.DROP_LATEST option does not have effect either
d

Dominaezzz

07/10/2021, 1:52 PM
Yes but isn't the
produceIn
a subscriber?
👍 1
👀 1
If I call
stream.emit(Unit)
20 times, in a row, it suspends after the 15th
emit
.
Nvm, it just never suspends.
m

mbonnin

07/10/2021, 1:59 PM
I got it to suspend at the 65th emission, which seems to indicate a default buffer size somewhere
Copy code
stream.buffer(10)
suspends at the 11th emission so looks like
Channel.RENDEZVOUS
isn't honoured
d

Dominaezzz

07/10/2021, 2:01 PM
Tried 200 emissions and it doesn't suspend.
That's odd. I'll try
buffer(10)
m

mbonnin

07/10/2021, 2:01 PM
I run this in a junit test:
Copy code
@Test
  fun produceIn() {
    runBlocking {
      val stream = MutableSharedFlow<Unit>()
      val unused = stream.buffer(Channel.RENDEZVOUS).produceIn(GlobalScope)
      var i = 0
      while (true) {
        println("emitting $i")
        stream.emit(Unit)
        i++
      }
    }
  }
using coroutine 1.5.0
d

Dominaezzz

07/10/2021, 2:03 PM
That stops at 75 for me.
m

mbonnin

07/10/2021, 2:03 PM
Interesting 👀
d

Dominaezzz

07/10/2021, 2:04 PM
Adding a delay before the loop makes it 65.
m

mbonnin

07/10/2021, 2:04 PM
SharedFlow doesn't support
RENDEZVOUS
:
Copy code
Application of flowOn, buffer with RENDEZVOUS capacity, or cancellable operators to a shared flow has no effect.
That might be part of the explanation
d

Dominaezzz

07/10/2021, 2:04 PM
Nooooo!!!
😐 1
Crap
I really don't want to use a channel for this. I guess I don't have a choice.
m

mbonnin

07/10/2021, 2:06 PM
I guess having a RENDEZVOUS with multiple subscribers was too complex...
d

Dominaezzz

07/10/2021, 2:08 PM
Thanks for helping find that.
There's still the issue of 65 emissions, I wonder where that comes from.
Ah,
buffer(1)
makes it 2. 🤦🏼
Doesn't seem like a complexity issue, but I'm now wondering why they thought it'd be meaningless.
Must've not realised there would be an interesting default?
It's probable
produceIn
that's wrong I guess.
8 Views