Pro Tip: Please remember that even if you just imp...
# feed
h
Pro Tip: Please remember that even if you just implement a suspending function, and you specify some cleanup in the
finally
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 @marcinmoskala
e
why this example does not print
Coroutine finished
? (taken from the article):
Copy code
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
m
I’d say because the launched job gets cancelled while suspending in the
delay(200)
, so the
println("Coroutine finished")
does not get called.
👍 1
e
oh because of the cancellation exception. Makes sense, thanks
for some reason I completely missed the
cancelAndJoin
call later.