0
0
Kotlinprogramming~10 mins

Job lifecycle and cancellation in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to wait for a coroutine job to complete.

Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    println("Job started")
}
job.[1]
Drag options to blanks, or click blank then click option'
Astart()
Bjoin()
Ccancel()
Dinvoke()
Attempts:
3 left
💡 Hint
Common Mistakes
Using cancel() instead of join() will stop the job instead of waiting.
start() is not needed because launch starts the job immediately.
2fill in blank
medium

Complete the code to cancel a running coroutine job.

Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    repeat(1000) { i ->
        println("Job is working on task $i")
        delay(100L)
    }
}
job.[1]
Drag options to blanks, or click blank then click option'
Acancel()
Bstart()
Cjoin()
Dinvoke()
Attempts:
3 left
💡 Hint
Common Mistakes
Using join() waits for completion but does not cancel.
start() is not used to stop a job.
3fill in blank
hard

Fix the error in the code to check if a job is active.

Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    delay(1000L)
}
if (job.[1]) {
    println("Job is still active")
}
Drag options to blanks, or click blank then click option'
AisCompleted
BisCancelled
CisActive
DisRunning
Attempts:
3 left
💡 Hint
Common Mistakes
Using isCancelled checks if the job was cancelled, not if active.
isCompleted means the job finished, not active.
4fill in blank
hard

Fill both blanks to create a coroutine that cancels itself after delay.

Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    delay(500L)
    job.[1]()
}
job.[2]()
Drag options to blanks, or click blank then click option'
Acancel
Bjoin
Cstart
Dinvoke
Attempts:
3 left
💡 Hint
Common Mistakes
Using start() instead of cancel() inside coroutine.
Not waiting for job completion with join().
5fill in blank
hard

Fill all three blanks to create a job that checks cancellation and handles it.

Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    try {
        repeat(100) {
            if (!job.[1]) {
                println("Job cancelled")
                return@launch
            }
            println("Working on task $it")
            delay(100L)
        }
    } catch (e: [2]) {
        println("Caught cancellation exception")
    }
}
job.[3]()
Drag options to blanks, or click blank then click option'
AisActive
BCancellationException
Cjoin
DisCancelled
Attempts:
3 left
💡 Hint
Common Mistakes
Checking isCancelled instead of isActive.
Catching wrong exception type.
Not waiting for job completion.