0
0
Kotlinprogramming~30 mins

Job lifecycle and cancellation in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Job lifecycle and cancellation
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use println("Job active: $isJobActive") and println("Job completed: $isJobCompleted") to show the job status.