Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I missing here?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading