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

Marc Knaup

01/01/2021, 4:10 PM
I still struggle with fully understanding scopes & contexts. Let’s say I have two scopes and would like to perform some suspendable work that is canceled if either of the two scopes is canceled. Is this sufficient?
Copy code
withContext(scope1.coroutineContext) {
    withContext(scope2.coroutineContext) {
        doSomeWork()
    }
}
Similarly with `Job`:
Copy code
val context2 = scope1.coroutineContext + SupervisorJob()

withContext(scope1.coroutineContext) {
     withContext(context2) {
         doSomeWork()
     }
}
Would the cancellation of one context affect the other context? Is that the proper way to do that?
m

Marc Knaup

01/01/2021, 4:55 PM
Thank you, that’s exactly the use case: https://github.com/Kotlin/kotlinx.coroutines/issues/1001#issuecomment-478337694 I’ve always assumed that it already works out of the box as it’s such a common use case (at least for me). But turns out the behavior is quite different from what I’ve expected 😕
3 Views