Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 213
vach Avatar asked Jan 26 '23 17:01

vach


1 Answers

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
like image 164
Sergey Avatar answered Apr 27 '23 19:04

Sergey