import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlin.random.Random
fun randomSharedFlow(): Flow<Int> {
val sharedFlow = MutableSharedFlow<Int>()
GlobalScope.launch(Dispatchers.Default) {
for (i in 0 until 10) {
sharedFlow.emit(Random.nextInt(1,100))
delay(200)
}
}
return sharedFlow
}
fun main() {
val sharedFlow = randomSharedFlow()
GlobalScope.launch(Dispatchers.Default) {
sharedFlow.collect { println("Collector A: $it") }
println("That's all folks!")
}
GlobalScope.launch(Dispatchers.Default) {
sharedFlow.collect { println("Collector B: $it") }
println("That's all folks!")
}
println("...and we're off!")
}
If this code is run in Intellij Idea, the result is only: …and we’re off!"
If it is run on kotlin Playground: I did receive some values like this: Collector B: 22 Collector A: 22 Collector B: 52 .
Also, why isn’t “That’s all folks!” printed?
Thank you for reading.