Halina
03/11/2024, 11:38 AMfinally
block, and this cleanup requires a suspending call, you should use withContext(NonCancellable)
it to make sure that the cleanup will be done even in case of cancellation. 👇
https://kt.academy/article/cc-cancellation#just-one-more-call by @marcinmoskalaEndre Deak
03/11/2024, 2:50 PMCoroutine finished
? (taken from the article):
import kotlinx.coroutines.*
suspend fun main(): Unit = coroutineScope {
val job = Job()
launch(job) {
try {
println("Coroutine started")
delay(200)
println("Coroutine finished")
} finally {
println("Finally")
withContext(NonCancellable) {
launch {
println("Children executed")
}
delay(1000L)
println("Cleanup done")
}
}
}
delay(100)
job.cancelAndJoin()
println("Done")
}
// Coroutine started
// (0.1 sec)
// Finally
// Children executed
// (1 sec)
// Cleanup done
// Done
Mervyn McCreight
03/11/2024, 2:52 PMdelay(200)
, so the println("Coroutine finished")
does not get called.Endre Deak
03/11/2024, 3:20 PMEndre Deak
03/11/2024, 3:20 PMcancelAndJoin
call later.