Bugs Happen
Bugs Happen

Reputation: 2268

Kotlin - Coroutine not executing as expected

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?

Upvotes: 2

Views: 715

Answers (1)

Sergio
Sergio

Reputation: 30675

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.

Upvotes: 2

Related Questions