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

Allan Wang

01/23/2019, 4:27 AM
If I have a suspend function that does nothing but change contexts, how do I ensure that I catch any failures and ensure that my logic continues? My parent scope is already a supervisor job, and I try catch my suspended calls. However, I notice that I need to do so multiple times to ensure that I actually catch errors After some tests, I can use a
supervisorScope
and try catch it. However, it still doesn’t stop the cancellation of every other job, despite the main context already being a supervisor
d

Dico

01/23/2019, 9:08 AM
Try adding
NonCancellable
to your context
a

Allan Wang

01/23/2019, 2:41 PM
Does
NonCancellable
still allow
job.cancel()
? My use case:
Copy code
launch {
   // a
   suspendFunB()
   // c
}
launch {
  // d
}
Suspend B may crash, but I always want
a
and
c
to execute. I also want
d
to always execute without being affected by the previous launch. If the parent scope is cancelled, I’d like everything to cancel. Should
NonCancellable
be around
suspendFunB
or the first launch?
d

Dico

01/24/2019, 8:33 PM
As far as I'm concerned,
NonCancellable
means the coroutine ignores cancellation from
job.cancel()
. So I would do:
Copy code
launch(NonCancellable) {
   // a
   try {
     suspendFunB()
   } finally {
     // c
   }
}
a

Allan Wang

01/24/2019, 10:23 PM
the problem is that even if c runs, if it does something like offer a value to a channel, which receives the events in d, d ends up getting cancelled and nothing happens. I just want it so that no matter what happens in suspendFunB, it will not cancel anything else or pass an exception elsewhere
And I wouldn’t want to wrap d in noncancellable because I do want all parts to cancel if the
job.cancel()
is called.
2 Views