kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

launch creates another child job

Open dovchinnikov opened this issue 3 years ago • 1 comments

@OptIn(InternalCoroutinesApi::class)
@Suppress("DEPRECATION_ERROR", "INVISIBLE_MEMBER")
fun main() {
  runBlocking {
    launch(SupervisorJob()) {
      // failed child cancels parent, 
      // which turns out not to be a supervisor, 
      // but a regular StandaloneCoroutine
      async {
        throw RuntimeException("child failure")
      }
      // one can verify it 
      val thisJob = coroutineContext.job
      println(thisJob) // StandaloneCoroutine
      println((thisJob as JobSupport).parentHandle?.parent) // SupervisorJobImpl
    }.join()
  }
}

Basically, this is equivalent to

CoroutineScope(coroutineContext + SupervisorJob()).launch {
  ...
}

which, at least, is obvious.

dovchinnikov avatar Aug 25 '22 11:08 dovchinnikov

I'm not sure what title to give to this issue, there are several interlinked problems.

  • one cannot launch a supervisor coroutine;
  • the Job in the context is used as a parent for launch;
  • it's too easy to break from the parent-child hierarchy with explicitly created Job;
  • even if the Job is created with a proper parent, no one will complete the Job passed into launch.

dovchinnikov avatar Aug 25 '22 11:08 dovchinnikov