Skip to content

"withContext" and "prompt cancellation guarantee" #2383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yvolk opened this issue Nov 12, 2020 · 2 comments
Closed

"withContext" and "prompt cancellation guarantee" #2383

yvolk opened this issue Nov 12, 2020 · 2 comments
Labels
docs KDoc and API reference

Comments

@yvolk
Copy link

yvolk commented Nov 12, 2020

KDoc for the withContext function (

* when it completes. Note that the result of `withContext` invocation is
) says:

Note that the result of withContext invocation is dispatched into the original context in a cancellable way with a prompt cancellation guarantee,
which means that if the original [coroutineContext], in which withContext was invoked,
is cancelled by the time its dispatcher starts to execute the code,
it discards the result of withContext and throws [CancellationException].

But this example https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-cancel-05.kt
shows that even if the job is cancelled, "withContext" (in the finally block) starts normally.

I even checked this adding two lines inside finally block:

...
    } finally {
        println("Context in finally:  coroutineContext isActive:${coroutineContext.isActive}")
        println("Context in finally:  job isCancelled:${coroutineContext[Job]?.isCancelled}")
        withContext(NonCancellable) {
            println("job: I'm running finally")
...

and get this:

Context in finally:  coroutineContext isActive:false
Context in finally:  job isCancelled:true
job: I'm running finally

As I understand, either documentation or behavior should be changed.

@yvolk
Copy link
Author

yvolk commented Nov 12, 2020

Looks like copy-paste bug?!

@elizarov
Copy link
Contributor

That's a subtle effect of a combination of withContext and NonCancellable and it works so by design. I'll see how it could be properly documented.

elizarov added a commit that referenced this issue Nov 18, 2020
@qwwdfsad qwwdfsad added the docs KDoc and API reference label Nov 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs KDoc and API reference
Projects
None yet
Development

No branches or pull requests

3 participants