0
0
Kotlinprogramming~5 mins

Job lifecycle and cancellation in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a Job in Kotlin coroutines?
A Job represents a cancellable task or coroutine. It controls the coroutine's lifecycle, allowing you to start, cancel, or check its status.
Click to reveal answer
intermediate
Name the main states in a Job's lifecycle.
The main states are:
  • New: Created but not started.
  • Active: Running or suspended.
  • Completing: Finishing work.
  • Cancelled: Stopped before completion.
  • Completed: Finished successfully.
Click to reveal answer
beginner
How do you cancel a Job in Kotlin?
You call the cancel() function on the Job instance. This requests cancellation, and the coroutine cooperatively stops if it checks for cancellation.
Click to reveal answer
intermediate
What happens if a coroutine ignores cancellation?
If a coroutine does not check for cancellation (e.g., by calling yield() or checking isActive), it may continue running even after cancel() is called, delaying cancellation.
Click to reveal answer
intermediate
Explain cooperative cancellation in Kotlin coroutines.
Cooperative cancellation means the coroutine must regularly check if it is cancelled and stop work accordingly. This is done by checking isActive or using cancellable suspending functions.
Click to reveal answer
Which function is used to stop a running Job in Kotlin?
Acancel()
Bstop()
Cterminate()
Dend()
What state is a Job in when it has finished successfully?
AActive
BCancelled
CNew
DCompleted
What must a coroutine do to respond to cancellation?
ACheck for cancellation cooperatively
BIgnore cancellation requests
CCall cancel() on itself
DRun on a separate thread
Which of these is NOT a Job lifecycle state?
ANew
BActive
CPaused
DCancelled
What happens if you call cancel() on a Job but the coroutine never checks for cancellation?
AThe coroutine stops immediately
BThe coroutine ignores cancellation and keeps running
CAn error is thrown
DThe Job restarts automatically
Describe the lifecycle of a Kotlin Job and how cancellation affects it.
Think about how a Job moves from new to completed or cancelled.
You got /4 concepts.
    Explain why cooperative cancellation is important in Kotlin coroutines.
    Consider what happens if a coroutine ignores cancellation.
    You got /4 concepts.