just a PSA: be careful when you create a new `Coro...
# coroutines
z
just a PSA: be careful when you create a new
CoroutineScope
and make sure realize the side effects of breaking structured concurrency. ex:
CoroutineScope(Dispatchers.Default)
explicitly breaks structured concurrency. This has testing implications like passing tests even when exceptions are thrown https://gist.github.com/ZakTaccardi/e77d5983660ce4e8e0fa2f2ef0d582ea
o
FYI a better way to do the second test is:
Copy code
parentScope.launch(Dispatcher.UNCONFINED) {
            throw Exception("fail")
        }
            .join()
no reason to do the addition yourself
đź‘Ť 1
s
Yup. Using another/new CoroutineScope instance is like switching to another/new lifecycle. The calling CoroutineScope’s lifecycle is no longer honored inside the new one. If you want to switch dispatcher or something, use
withContext(myDispatcher)
or
launch(myDispatcher)
etc.
đź‘Ť 1
It has its uses, though, switching between lifecycles by running coroutines on different CoroutineScopes. But you’ll have to be careful 🙂
a
IMO structured concurrency is very fragile and you need to be very careful not to break it. Without experience is not possible to maintain structured concurrency and you barely can know is it works or not. E.g. when you are doing CoroutineScope.launch(context + Job()) structure concurrency is immediately So actually CoroutineScope.launch(context + Job()) is equals to GlobalScope.launch(context + Job())
I've written couple helper functions to cope with this effects: https://github.com/Kotlin/kotlinx.coroutines/issues/1001#issuecomment-473278219