CoroutineScope Questions

Viewed 43

At the Coroutine Scope, Why is the last println() called first when the launch block is called first?

enter image description here

enter image description here

2 Answers

Hej BrianLee,

within the runBlocking you start two new coroutines without blocking the current thread when calling launch{}. So the block inside runBlocking continues and the printlns are executed.

If you want to want for the launch-blocks to finish first, you have to make your thread wait for its execution by use .join() on its Job

runBlocking {
 val job = launch {
   println("launch : ${Thread.currentThread() .name}")
   println("launch 1")
 }

 job.join()
 
 println("runBlocking: ${Thread. currentThread () .name}")
 println("runBlockging")
}

Link: https://kotlinlang.org/docs/coroutines-basics.html#an-explicit-job

Launch is a coroutine builder. It launches a new coroutine concurrently with the rest of the code, which continues to work independently. That's why outside code is executed and printed first.

Try with suspend function with coroutineScope

Use suspend function

Reference take here. Mentioned in kotlin docs https://kotlinlang.org/docs/coroutines-basics.html#scope-builder

fun main() = runBlocking{  
 doWork()
}
fun doWork() = coroutineScope{  

  launch{
    //your code here
    }
}
Related