vach
vach

Reputation: 11387

Coroutines the proper way to add a job as child of another?

Given we have job1 : Job and job2 : Job and we want to make job2 a child of job1 (they where created separately have no relation).

What is the correct way to declare that relationship? so that when job1 is cancelled job2 is cancelled as well...

I tried job1.attachChild(e1.job2 as ChildJob) but this is internal api. I do not want to do some hack when i launch job2 from job1 coroutine.

Upvotes: 5

Views: 2363

Answers (2)

Sergio
Sergio

Reputation: 30745

You can use a Job(parent: Job?) factory function which receives parent job as a parameter. It has the following definition:

public fun Job(parent: Job? = null): Job

that means parameter parent is an optional. So you can create your jobs like this:

var parentJob: Job = Job()
var childJob: Job = Job(parentJob)

Also take a look at SupervisorJob, which can be used to customize the default behavior of the Job. SupervisorJob factory function has similar definition:

fun SupervisorJob(parent: Job? = null): Job

Upvotes: 6

TomH
TomH

Reputation: 2729

Simply launch job2 from inside the scope of job1. Job2 will inherit the scope, and so if job1 is cancelled then so is job2.

Upvotes: 3

Related Questions