https://kotlinlang.org logo
Title
a

ansman

08/31/2020, 3:56 PM
I suppose I could get the parent job inside my non cancellable block and add a cancellation listener which throws a cancellation exception
b

bezrukov

08/31/2020, 5:28 PM
You should be able simply pass parentJob to withContext instead of noncancellable
a

ansman

08/31/2020, 5:29 PM
Ah, of course. A much more elegant solution 👌
I probably need an
ensureActive()
after my
withContext
since I don't think it'll throw if the job has been cancelled during the delay
b

bezrukov

08/31/2020, 5:32 PM
Nope, it should work as is
a

ansman

08/31/2020, 5:45 PM
Did they change this? I thought it was only when it resumes it checks for this?
No, I need an `ensureActive()`:
runBlocking {
    val parent = Job()
    val child = launch {
        withContext(parent) {
            delay(100L)
        }
        println("After")
    }
    delay(50L)
    child.cancel()
}
This code still prints after
Adding a
ensureActive()
before
println
it works as expected
b

bezrukov

08/31/2020, 5:50 PM
Ah, i thought you're about putting ensureActive directly after delay (withing withcontext block)
a

ansman

08/31/2020, 5:50 PM
Ah, yeah that'd do nothing haha