Jobs help manage background tasks in Kotlin. Understanding their lifecycle and how to stop them safely keeps your app responsive and efficient.
Job lifecycle and cancellation in 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.
val job = CoroutineScope(Dispatchers.Default).launch { println("Job started") delay(1000) println("Job finished") } job.cancel()
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") }
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.
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}") }
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.
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.