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 not waiting for a coroutine to finish?

I’m learning coroutines and am a little confused by something

import kotlinx.coroutines.*

@OptIn(DelicateCoroutinesApi::class)
fun main() {
    println("[${Thread.currentThread().name}] In main thread")

    GlobalScope.launch {
        println("[${Thread.currentThread().name}] In coroutine")
        repeat(4) {
            println("$it")
        }
    }
}

When I run this code, the output is a little unpredictable, sometimes I get output from the couroutines, sometimes I don’t..

enter image description here

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

enter image description here

could someone please explain what is causing this? Thank you!

>Solution :

I believe there are a few options, but the heart of the matter is the main thread believes your program is done, so it ends the program. You need to wait for the coroutine to complete. Try the below block. It waits for the coroutine to complete before proceeding:

val job = GlobalScope.launch {
    println("[${Thread.currentThread().name}] In coroutine")
    repeat(4) {
        println("$it")
    }
}

job.join()

more info can be found here, https://kotlinlang.org/docs/coroutines-basics.html#an-explicit-job

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