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

benny.huo

04/16/2019, 11:31 PM
Hey guys! I’m wondering if there’s a problem in the comment of
join
function:
l

louiscad

04/16/2019, 11:59 PM
I think it's not so up to date. Calling
join()
doesn't throw if the job is cancelled but didn't crash (i.e. threw a
CancellationException
)
b

benny.huo

04/17/2019, 12:05 AM
But I got a CancellationException when throws an Exception in the coroutine:
Copy code
suspend fun main() {
    log(1)
    val job = GlobalScope.launch(Dispatchers.Unconfined) {
        log(2)
        val job2 = launch(Dispatchers.Default) {
            log(3)
            val x = 1 / 0
            log(4)
        }
        // if falls in the fast-path, a CancellationException will be thrown.
        job2.join() 
        log(5)
    }
    log(6)
    job.join()
    log(7)
}
l

louiscad

04/17/2019, 12:12 AM
Do not use GlobalScope for this kind of stuff.
Use
coroutineScope { … }
b

benny.huo

04/17/2019, 12:20 AM
Is there any problem with
GlobeScope
? I changed to
coroutineScope{...}
and it seems to work normally.
l

louiscad

04/17/2019, 12:22 AM
Yes, it's global
b

benny.huo

04/17/2019, 12:25 AM
I cannot figure out the difference. When should we use
GlobalScope
?
s

streetsofboston

04/17/2019, 12:51 AM
coroutineScope
inherits its scope (the receiver of the lambda) from the calling/outer scope. Using GlobalScope here will cause you to switch scope from the calling one to the GlobalScope. Cancelation and error-handling may get wonky... Use GlobalScope if a coroutine runs as part of an object with a global lifecycle, eg a singleton global object.
2
b

benny.huo

04/17/2019, 1:39 AM
Thanks a lot.
v

Vsevolod Tolstopyatov [JB]

04/17/2019, 11:45 AM
This is outdated documentation, I will fix it, thanks
b

benny.huo

04/17/2019, 11:18 PM
After I change to
coroutineScope
, CancallationException still happens when the child job’s
join()
is called. Just like GlobalScope does.
This is the result of the slow path
joinSuspend
.
This is the result of the fast path.
So the question is should we get a CancellationException when join on the crashing or crashed child job? I seems we will get the cancellation when join on a crashed child job while not on a crashing child job.
Finally, I figure out that when child job crashed, parent job will be canceled according to the propagation of exception thus making the
join()
call on child job canceled. While join on the running child job, when exception throws, the suspended join returns with a Unit and the parent job will be canceled later on. That makes sense although confusing.
l

louiscad

04/18/2019, 4:52 AM
CancellationException
is not considered as a crash, but other throwables are.
2 Views