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

zak.taccardi

04/22/2020, 9:11 PM
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

octylFractal

04/22/2020, 9:19 PM
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

streetsofboston

04/22/2020, 10:13 PM
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

Antanas A.

04/23/2020, 7:58 AM
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
4 Views