Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
The join() function waits for the coroutine job to complete.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using join() waits for completion but does not cancel.
start() is not used to stop a job.
✗ Incorrect
The cancel() function stops the coroutine job.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using isCancelled checks if the job was cancelled, not if active.
isCompleted means the job finished, not active.
✗ Incorrect
The isActive property tells if the job is currently running.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using start() instead of cancel() inside coroutine.
Not waiting for job completion with join().
✗ Incorrect
The coroutine calls cancel() to stop itself, and the main code waits with join().
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking isCancelled instead of isActive.
Catching wrong exception type.
Not waiting for job completion.
✗ Incorrect
The job checks isActive to detect cancellation, catches CancellationException, and the main code waits with join().