-
Notifications
You must be signed in to change notification settings - Fork 24
How Job in coroutine works
Devrath edited this page Oct 9, 2021
·
16 revisions
- A coroutine returns a Job
- Using the Job we can create control the coroutine like stopping it, So a Job on a coroutine is a handle to the coroutine.
- More flexibility can be achieved using jobs, we can combine the instances of jobs using
join()
. - Say
Job-A
invokesjoin
onJob-B
the former won't be executed until later has finished on execution. - We can also set up a parent and child relation using which we can ensure parent won't complete until the child has completed its execution.
-
New-State
:-> When you launch a co-routine, you can create a job, It returns a new state. -
Active-State
:->- Once the coroutine is started the job goes from
new-state
intoactive-state
by default. - If you have started the co-routine by
LAZY
then you need to invokestart()
orjoin()
to make job go fromnew-state
intoactive-state
. - A running co-routine is always in
active-state
. At any point, a running co-routine can becanceled
orcompleted
. - We can check if a job is in
active-state
. - We can also check by looping the Job to check its children and do something for a particular state of the child.
- Once the coroutine is started the job goes from
-
Cancelling-State
:->- Once you launch a coroutine, many things can possibly happen
- Exception might occur
- Because of some new condition, We might need to cancel the job.
- Usually the
uncaught exception
causes the entire program to crash, but since the coroutines have suspending behavior, the exception can also be suspended and handled or managed later - We can cancel a job by calling
cancel()
on the job's reference, The job along with all its children's jobs are also cancelled. - If a Job has a parent and the job is canceled, The parent job is also cancelled.
- Once you launch a coroutine, many things can possibly happen