-
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-AinvokesjoinonJob-Bthe 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-stateintoactive-stateby default. - If you have started the co-routine by
LAZYthen you need to invokestart()orjoin()to make job go fromnew-stateintoactive-state. - A running co-routine is always in
active-state. At any point, a running co-routine can becanceledorcompleted. - 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 exceptioncauses 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
