https://kotlinlang.org logo
#feed
Title
# feed
h

Halina

03/11/2024, 11:38 AM
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

Endre Deak

03/11/2024, 2:50 PM
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

Mervyn McCreight

03/11/2024, 2:52 PM
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

Endre Deak

03/11/2024, 3:20 PM
oh because of the cancellation exception. Makes sense, thanks
for some reason I completely missed the
cancelAndJoin
call later.
2 Views