Complete the code to wait for a coroutine job to complete.
val job = CoroutineScope(Dispatchers.Default).launch {
println("Job started")
}
job.[1]The join() function waits for the coroutine job to complete.
Complete the code to cancel a running coroutine job.
val job = CoroutineScope(Dispatchers.Default).launch {
repeat(1000) { i ->
println("Job is working on task $i")
delay(100L)
}
}
job.[1]The cancel() function stops the coroutine job.
Fix the error in the code to check if a job is active.
val job = CoroutineScope(Dispatchers.Default).launch {
delay(1000L)
}
if (job.[1]) {
println("Job is still active")
}The isActive property tells if the job is currently running.
Fill both blanks to create a coroutine that cancels itself after delay.
val job = CoroutineScope(Dispatchers.Default).launch {
delay(500L)
job.[1]()
}
job.[2]()The coroutine calls cancel() to stop itself, and the main code waits with join().
Fill all three blanks to create a job that checks cancellation and handles it.
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]()The job checks isActive to detect cancellation, catches CancellationException, and the main code waits with join().
