Hi Team, I understand that runBlocking waits for c...
# coroutines
s
Hi Team, I understand that runBlocking waits for coroutines launched from its scope to wait. However when I create a new scope using runBlocking scope's coroutine context, runBlocking will wait for the coroutines launched from this new scope. My question is what parameter of coroutine context does runBlocking use to decide if it wants to wait for a launched coroutine. If you have any resources for the inner workings of runBlocking please provide them. Thanks.
s
It uses structured concurrency. The runBlocking will block until its CoroutineScope ends. A CoroutineScope ends only after all its children (jobs/coroutines) have ended. Creating a brand-new CoroutineScope would allow you to let 'child' coroutines running after the main/parent CoroutineScope has ended (two different lifecycles). But you share the CoroutineContext between the parent and the newly created CoroutineScope, thus sharing the Job stored in that CoroutineContext, and Jobs govern the ending/cancellation of the parent and the children. Replace that shared Job with a brand new Job in the new CoroutineScope. That should allow 'child' jobs/coroutines to keep running:
CorountineScope(coroutineContext + Job())
s
"Replace that shared Job with a brand new Job in the new CoroutineScope. That should allow 'child' jobs/coroutines to keep running:
CorountineScope(coroutineContext + Job())"
Tried this exactly, but runBlocking still waits for coroutines launched in this scope. This was the first thing that I tried doing actually,
g
Could you show some reproducible code snippet
My question is what parameter of coroutine context does runBlocking use to decide if it wants to wait for a launched coroutine.
As Anton staid, any scope/job/context created from runBlocking scope as parent will be linked to runBlocking
s
@gildor @streetsofboston You are right. In this case runBlocking does not wait
Copy code
@Test
fun coroutineTest19() = runBlocking {
    val newScope = CoroutineScope(coroutineContext + Job())
    newScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        var count = 0
        while(true){
            Thread.sleep(1000)
            println("Hello ${count++}")
        }
    }
    Unit
}
In this case runBlocking does wait.
Copy code
@Test
fun coroutineTest19() = runBlocking {
    val newScope = CoroutineScope(coroutineContext)
    newScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        var count = 0
        while(true){
            Thread.sleep(1000)
            println("Hello ${count++}")
        }
    }
    Unit
}
I had somehow gotten confused. Thanks for your help
g
What are you trying to achieve with this code? Because both look somewhat wrong for me. Are you doing this for tests?
s
I am writing a post explaining coroutines.
g
I see, be free to share it 👍