Reputation: 285
When runBlocking is used the lines are getting printed but in the following case its not printing anything
fun main(){
GlobalScope.launch{
println("function started") //printing the first line
delay(1000)
println("function ended") //printing the last line
}}
Upvotes: 3
Views: 1178
Reputation: 37730
You program terminates before the launched coroutine has a chance to start.
launch
starts an asynchronous piece of code, so the program can keep going after calling launch
without waiting for the body of launch
to execute. There is nothing in your current code that waits for this coroutine to finish before terminating the program, so the program just ends.
When runBlocking is used the lines are getting printed
I'm assuming you're referring to running it this way:
fun main(): Unit = runBlocking { // this: CoroutineScope
launch {
println("function started") //printing the first line
delay(1000)
println("function ended") //printing the last line
}
}
runBlocking
here defines a CoroutineScope
that is available as this
inside the lambda. The launch
here is launched in that scope, which makes it a child coroutine of runBlocking
.
By definition, runBlocking
blocks the current thread (the main thread here) until all child coroutines are completed. This is why in that case the program waits for the coroutine to complete.
If you're just learning coroutines, you should really avoid using delicate APIs like GlobalScope
. Instead, try to stick with structured concurrency. Structured concurrency is a way to structure your coroutines with parent-child relations so that you don't get surprised by coroutine leaks (like this one).
Upvotes: 6