I've seen some code similar to this: ```fun main(...
# coroutines
n
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
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
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
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)