📖 Scenario: You are building a simple Kotlin program that uses coroutines to run a background task. You want to understand how to start a job, check its status, and cancel it properly.
🎯 Goal: Learn how to create a coroutine Job, check if it is active or completed, and cancel it safely.
📋 What You'll Learn
Create a coroutine Job that runs a simple repeating task
Add a variable to hold the Job
Use coroutine lifecycle properties like isActive and isCompleted
Cancel the Job and print its status
💡 Why This Matters
🌍 Real World
Understanding job lifecycle and cancellation is important when running background tasks in Android apps or server applications to avoid wasting resources.
💼 Career
Many Kotlin developer roles require knowledge of coroutine management to write efficient and responsive asynchronous code.
Progress0 / 4 steps
1
Create a coroutine Job with a repeating task
Write code to create a coroutine Job named job that runs a repeating task printing "Working..." every 300 milliseconds inside a GlobalScope.launch. Use delay(300) inside the coroutine. Import necessary coroutine libraries.
Kotlin
Hint
Use GlobalScope.launch to start a coroutine and assign it to job. Use repeat(5) to print "Working..." five times with delay(300) between prints.
2
Add a variable to check job status
Add a variable named isJobActive that stores the job.isActive property after starting the job.
Kotlin
Hint
After launching the job, create val isJobActive = job.isActive to check if the job is running.
3
Cancel the job and check completion
Call job.cancel() to cancel the job. Then add a variable isJobCompleted that stores job.isCompleted.
Kotlin
Hint
Use job.cancel() to stop the job and then check job.isCompleted to see if it finished.
4
Print job status after cancellation
Print the values of isJobActive and isJobCompleted using println statements.
Kotlin
Hint
Use println("Job active: $isJobActive") and println("Job completed: $isJobCompleted") to show the job status.
Practice
(1/5)
1. Which of the following best describes the lifecycle of a Kotlin Job?
easy
A. A job is always active and never completes.
B. A job starts cancelled and then becomes active.
C. A job starts active, can be cancelled, and then completes.
D. A job completes before it starts.
Solution
Step 1: Understand Job lifecycle states
A Kotlin Job begins in an active state, meaning it is running or ready to run.
Step 2: Recognize cancellation and completion
A Job can be cancelled to stop its work, and after finishing or cancellation, it reaches a completed state.
Final Answer:
A job starts active, can be cancelled, and then completes. -> Option C
Quick Check:
Job lifecycle = active -> cancelled -> completed [OK]
Hint: Jobs start active, then cancel or complete [OK]
Common Mistakes:
Thinking jobs start cancelled
Assuming jobs never complete
Confusing job states order
2. Which Kotlin code snippet correctly cancels a job and waits for its completion?
easy
A. job.cancelAndJoin()
B. job.cancel()
C. job.start()
D. job.join()
Solution
Step 1: Identify cancellation with waiting
The method cancelAndJoin() cancels the job and suspends until it finishes.
Step 2: Differentiate from other methods
cancel() only requests cancellation without waiting; join() waits but doesn't cancel; start() begins a job.
Final Answer:
job.cancelAndJoin() -> Option A
Quick Check:
Cancel and wait = cancelAndJoin() [OK]
Hint: Use cancelAndJoin() to cancel and wait [OK]
Common Mistakes:
Using cancel() without waiting
Confusing join() with cancel
Calling start() to cancel
3. What will be the output of this Kotlin coroutine code?
val job = CoroutineScope(Dispatchers.Default).launch {
repeat(3) { i ->
println("Working on $i...")
delay(100)
}
}
job.cancel()
Thread.sleep(500)
medium
A. Prints all three "Working on" lines
B. Prints some "Working on" lines before stopping
C. Throws a cancellation exception
D. Prints no output
Solution
Step 1: Analyze job launch and cancellation
The job starts and prints "Working on 0...", then delays. The cancel() is called immediately after launch.
Step 2: Understand cancellation effect
Because cancellation happens quickly, some iterations may run before the job stops, so partial output appears.
Final Answer:
Prints some "Working on" lines before stopping -> Option B
Quick Check:
Partial output due to quick cancel [OK]
Hint: Cancel stops job but may print partial output [OK]
Common Mistakes:
Expecting all lines printed
Expecting no output at all
Assuming exception is printed
4. Identify the error in this Kotlin coroutine cancellation code: