https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

Norbi

01/25/2023, 9:41 PM
I've seen some code similar to this:
Copy code
fun main() {
    runBlocking {
        withContext(Job() + ...) {
            ...
        }
    }
}
What is the reason for creating a new
Job
instance for the
withContext()
call? Thanks.
s

Sam

01/25/2023, 10:02 PM
Not much. It's somewhat equivalent to
withContext(NonCancellable)
in that it will stop the jobs in the inner scope from being cancelled by a cancellation of the outer scope. It has no other effect.
c

Casey Brooks

01/25/2023, 10:06 PM
Do you have an example in a library or something similar where this pattern is done? My initial though is that this is more likely a bug than something done intentionally. You generally shouldn’t override the Job without linking it to the parent Job, as that would prevent cancellation of the inner code block when the outer coroutine gets cancelled.
n

Norbi

01/26/2023, 8:09 AM
Do you have an example in a library or something similar
Sorry, I don't find it, I've seen this pattern in Medium articles (of the same author) when I looked for some info...
In the meantime, I have also found this:
No.
Copy code
withContext(Job())
is a weird thing that you should never do as it breaks structured concurrency (we should have forbidden it, but we cannot due to backwards compatibility)
2 Views