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..
could someone please explain what is causing this? Thank you!
CodePudding user response:
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