0
0
Kotlinprogramming~10 mins

Job lifecycle and cancellation in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Job lifecycle and cancellation
Create Job
Start Job
Job Running
Cancel Job?
YesJob Cancelling
Job Cancelled
Cleanup
No
Job Complete
Job Finished
This flow shows how a Kotlin Job is created, started, runs, can be cancelled, and then finishes or cleans up.
Execution Sample
Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    repeat(3) {
        println("Working $it")
        delay(100)
    }
}
job.cancel()
This code starts a job that prints 'Working' three times with delays, but then cancels the job immediately.
Execution Table
StepActionJob StateOutputNotes
1Create job with launchNewJob is created but not started yet
2Job starts runningActiveJob begins execution of coroutine
3Iteration 0: printActiveWorking 0First loop iteration output
4Job.cancel() calledCancellingCancellation requested
5Check cancellation before iteration 1CancellingJob notices cancellation
6Job stops executionCancelledJob stops before printing 'Working 1'
7Job cleanupCancelledResources cleaned up, job finished
8Job is completeCancelledJob lifecycle ends
💡 Job is cancelled during execution, so it stops early and does not complete all iterations.
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 6Final
job.stateNewActiveCancellingCancelledCancelled
loop index (it)N/A0N/AN/AN/A
output"""Working 0\n""Working 0\n""Working 0\n""Working 0\n"
Key Moments - 3 Insights
Why does the job stop printing after 'Working 0'?
Because job.cancel() is called after the first print, the job state changes to Cancelling and then Cancelled, so the loop stops early as shown in steps 4 to 6 in the execution_table.
Is the job immediately stopped when cancel() is called?
No, the job moves to Cancelling state first and checks for cancellation cooperatively before stopping, as seen between steps 4 and 6.
What happens if we don't call cancel()?
The job runs all iterations and finishes normally, moving from Active to Completed state without interruption.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the job state at Step 5?
AActive
BCancelled
CCancelling
DCompleted
💡 Hint
Check the 'Job State' column at Step 5 in the execution_table.
At which step does the job print 'Working 0'?
AStep 2
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Output' column in the execution_table for the printed text.
If cancel() was called after Step 3, what would happen at Step 6?
AJob stops and becomes Cancelled
BJob is still Active
CJob continues running normally
DJob restarts
💡 Hint
Refer to how job.cancel() affects job state between Steps 4 and 6 in the execution_table.
Concept Snapshot
Job lifecycle in Kotlin:
- Create job with launch()
- Job starts in Active state
- Can be cancelled with cancel()
- Cancellation moves job to Cancelling then Cancelled
- Job stops cooperatively on cancellation
- Job finishes in Completed state if not cancelled
Full Transcript
This visual trace shows how a Kotlin Job is created, started, runs a loop printing 'Working' messages, and then is cancelled. The job starts in New state, moves to Active when running, and after cancel() is called, it moves to Cancelling and then Cancelled states. The job stops printing early due to cancellation. Variables like job.state and loop index change step by step. Key moments clarify why the job stops early and how cancellation works cooperatively. Quiz questions test understanding of job states and output timing.