'CoroutineScope Questions

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



Solution 1:[1]

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

Solution 2:[2]

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
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Knauf
Solution 2