Kotlin coroutine

Viewed 79

I try to understand how parent - child relationship works in that case

    private fun coroutineTest() {
        val job = CoroutineScope(Dispatchers.IO).launch {
            val standAloneJob = Job(coroutineContext.job)//this will create the relationship parent - child
            launch(standAloneJob) {
                delay(2000)
                Log.d(TAG,"I'm here")
            }
            delay(4000)
            if(standAloneJob.isCompleted) { // always false
               Log.d(TAG,"isCompleted")
             }
            //standAloneJob.complete() // without this line method invokeOnCompletion never called
        }

        job.invokeOnCompletion {
            Log.d(TAG,"invokeOnCompletion")
        }

    }

The question is why child coroutine initialized by standAloneJob never completed and as a consequence parent coroutine not completed too?

1 Answers

You do not need to manually create a job in order to set up parent-child relationship. It's done by default when using launch { .. } without overriding its job.

If you do create your own job like this, it becomes your responsibility to complete it.

standAloneJob here only acts as a parent for the nested launch's job, it's not the job of that launch:

val job = GlobalScope.launch {
    val standAloneJob = Job(coroutineContext.job)//this will create the relationship parent - child
    val child = launch(standAloneJob) {
        ...
    }
    println(child == standAloneJob) // false
    println(child in standAloneJob.children) // true
    ...
}

When the nested launch completes, its associated job is completed too, but it doesn't automatically complete its parent standAloneJob and thus it doesn't complete its grandparent coroutineContext.job.

Related