Home > OS >  Kotlin - Coroutine not executing as expected
Kotlin - Coroutine not executing as expected

Time:10-12

This couldn't be any simpler but I'm unable to understand what is the issue here. Here is my code:

fun main() {

    val flow = flowOf(1, 2, 3)

    CoroutineScope(Dispatchers.Default).launch {
        println("Launch working")
        flow.collect {
            println("Collect: $it")
        }
    }
}

The above code prints nothing, not even "Launch working". I even tried using my own CoroutineScope, like in the following code:

fun main() {

    val flow = flowOf(1, 2, 3)

    val myCoroutineScope = CoroutineScope(
        CoroutineName("myCoroutineScope")
    )

    myCoroutineScope.launch {
        println("My coroutine scope working")
        flow.collect {
            println("Collect: $it")
        }
    }
}

Again, it printed nothing, not even "My coroutine scope working".

What am I missing here?

CodePudding user response:

Please try to use runBlocking and Job.join() to wait for the coroutine to finish:

fun main() = runBlocking {

    val flow = flowOf(1, 2, 3)

    val job = CoroutineScope(Dispatchers.Default).launch {
        println("Launch working")
        flow.collect {
            println("Collect: $it")
        }
    }
    job.join()
}

It will block the execution of the main() function until the flow is collected.

  • Related