Hi, am I right that there's no way to distinguish ...
# coroutines
l
Hi, am I right that there's no way to distinguish whether a
CancellationException
is caused by a function call or by the cancellation of the coroutine scope? I'd like to handle cancellation caused by a function call without stopping suspending iteration, unless the whole scope is cancelled (because the Activity is destroyed)
🧵 1
e
What do you mean “caused by a function call”?
CancellationException
is only thrown when the scope (job) is cancelled
l
Caused by calling
cancel()
from a
CompletableDeferred
that is awaited. I had a
while(true) try { ... } catch(e: Exception) { ... }
, but I added a
coroutineScope { ... }
and did a
while(isActive)
instead to fix. BTW, I realized I could have made an infinite cancellation loop by adding cancellation support to a method without allowing cancellation to ever succeed.
e
The convention is that
CancellationException
is thrown on cancellation. So if you are writing an infinite loop and you want it to be cancellable, then you can either check for
isActive
or break when you catch
CancellationException
l
Yes, but I caught it, without rethrowing it, and moved on to the next iteration, which began in the try block that would throw the
CancellationException
, then caught again, and so on... Reading your words, I think I'm realizing it's not a good idea to throw a
CancellationException
that can't be disambiguated by its type like
TimeoutCancellationException
can for things like an alert dialog being dismissed so I'll create a
CancellationException
subclass and cancel the
CompletableDeferred
with it, so a coroutine calling it can recover safely if needed.