TareK Khoury
TareK Khoury

Reputation: 13021

Kotlin Coroutines Job hierarchy explanation

While reading an interesting article on Exception in Coroutines. I came across section that includes the following image:

Coroutine Job Hierarchy

I am trying to understand how and where did the parent Job come from?

Although they explain it the article as:

a new coroutine always gets assigned a new Job()

But looking at the code, I see a top level scope with a Job, when calling the "parent" launch we override it with a SupervisorJob and then two child launch which i guess inherit the parent job or create their own.

So, my question is where did the parent job came from (the one wrapping the 2 child jobs)?

Upvotes: 2

Views: 1713

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200148

What you pass to launch becomes the parent of the job that launch internally creates. That job is always of the same type, which is StandaloneCoroutine. You cannot control the Job instance corresponding to the coroutine, you can only decide on its parent.

In your diagram, the Job() inside the scope is completely ignored. The top-level launch creates its own StandaloneCoroutine and assigns the SupervisorJob you passed in as its parent.

In the particular situation represented in your diagram, SupervisorJob has no effect as it doesn't prevent any coroutine failure from spreading. The top-level launch will get cancelled if any of the two inner launch coroutines fail. The only difference will be that the SupervisorJob will remain active, but it will have no children at that point.

Upvotes: 2

Related Questions