BroadcastChannel Example does not work when using Run but works when using Debug

The following example from the book works when you use Debug, but not Run. I’m using a MacBook

Blockquote
fun main() {
val fruitArray = arrayOf(“Apple”, “Banana”, “Pear”, “Grapes”, “Strawberry”)
// 1
val kotlinChannel = BroadcastChannel(3) runBlocking {
// 2
kotlinChannel.apply {
send(fruitArray[0])
send(fruitArray[1])
send(fruitArray[2])
}
//3 Consumers
GlobalScope.launch {
// 4
kotlinChannel.openSubscription().let { channel →
// 5
for (value in channel) { println(“Consumer 1: $value”) }
// 6
}
}
GlobalScope.launch {
kotlinChannel.openSubscription().let { channel →
for (value in channel) { println(“Consumer 2: $value”) }
}
}
// 7
kotlinChannel.apply { send(fruitArray[3])
send(fruitArray[4]) }
// 8
println(“Press a key to exit…”) readLine()
// 9
kotlinChannel.close() }
}

@filbabic Can you please help with this when you get a chance? Thank you - much appreciated! :]

@shogunkaramazov I didn’t write this chapter. @nisrulz could probably help here more than me!

1 Like

@shogunkaramazov @nisrulz @filbabic as a side note Broadcast channel will become obsolete sometime in the near future once the shared flow API is stable.

quote from the docs: " Note: This API is obsolete. It will be deprecated and replaced by SharedFlow when it becomes stable."

The book does need an update. I will provide a work around in the meantime here.

1 Like