Skip to content

How Job in coroutine works

Devrath edited this page Oct 9, 2021 · 16 revisions

Defining the coroutine job

  • 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 invokes join on Job-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.

States of Jobs

  • 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 into active-state by default.
    • If you have started the co-routine by LAZY then you need to invoke start() or join() to make job go from new-state into active-state.
    • A running co-routine is always in active-state. At any point, a running co-routine can be canceled or completed.
    • 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.
  • 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.
Clone this wiki locally