0
0
Kotlinprogramming~5 mins

Job lifecycle and cancellation in Kotlin

Choose your learning style9 modes available
Introduction

Jobs help manage background tasks in Kotlin. Understanding their lifecycle and how to stop them safely keeps your app responsive and efficient.

When running a task in the background that might take time, like downloading a file.
When you want to stop a task early if the user leaves the screen.
When you need to clean up resources after a task finishes or is stopped.
When coordinating multiple tasks that depend on each other.
When you want to avoid wasting battery or CPU on tasks no longer needed.
Syntax
Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    // your background task here
}

// To cancel the job:
job.cancel()

// To check if job is active:
if (job.isActive) {
    // do something
}

launch starts a new job (background task).

cancel() stops the job safely.

Examples
This starts a job that prints messages but cancels it immediately, so "Job finished" may not print.
Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    println("Job started")
    delay(1000)
    println("Job finished")
}

job.cancel()
This runs a job that prints steps but cancels it after 1 second.
Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    repeat(5) { i ->
        println("Working on step $i")
        delay(500)
    }
}

// Cancel after 1 second
CoroutineScope(Dispatchers.Default).launch {
    delay(1000)
    job.cancel()
    println("Job cancelled")
}
Sample Program

This program starts a job that prints steps every 0.5 seconds. After about 1.2 seconds, it cancels the job. The job catches the cancellation, prints a message, and does cleanup. Finally, the main program confirms the job is done.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(5) { i ->
                println("Working on step $i")
                delay(500)
            }
        } catch (e: CancellationException) {
            println("Job was cancelled")
        } finally {
            println("Cleanup after job")
        }
    }

    delay(1200) // Let the job run a bit
    println("Requesting cancellation")
    job.cancelAndJoin() // Cancel and wait for job to finish
    println("Job is completed: ${job.isCompleted}")
}
OutputSuccess
Important Notes

Always handle CancellationException inside jobs to clean up resources.

Calling cancel() requests cancellation but does not wait; use cancelAndJoin() to wait until the job finishes.

A job is isActive while running and isCompleted after finishing or cancellation.

Summary

Jobs represent background tasks with a clear lifecycle: active, cancelled, completed.

You can stop jobs safely using cancel() or cancelAndJoin().

Handling cancellation lets you clean up and keep your app responsive.