Intellij idea does not show coroutine results but Kotlin Playgroun does

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.

Coroutines running in the background don’t keep the process alive. The application finishes before these coroutines have a chance to do anything. Maybe Playground is configured differently.

If you want to wait on something, then you should not use GlobalScope.launch() which by design doesn’t care about the result. Use runBlocking() and inside it launch() or something similar.

1 Like

Thank you very much for your help.