According to the docs, calling cancel
on a Job
cancels the running coroutine. Does calling cancel
again on the same Job
have any negative effects? I would assume it just does nothing, and that seems to be the case in practice, but I can't find anywhere in the documentation where it makes this explicit.
Is it safe to cancel
an already-canceled Job
?
A little explanation as to why I'm asking: I have a button that, when pressed, cancels a Job
. The Job
may not stop immediately, so it is possible for the user to tap the button more than once if they tap quickly. I need to know if I need to add code to ensure I only call cancel
once when the button is first pressed, or if it's okay for the button to call cancel
each time it is pressed. I know calling cancel
again won't make the coroutine stop any faster; I just need to know it's not going to cause problems!
KotlinX Coroutines Job#cancel
is idempotent, so no matter how many times you call cancel
it will achieve the same result.
Internally Job
already tracks it's state, so calling cancel
many times will not cause any issues as the cancel
function itself will never fail, or throw an exception.
A Job can only transition from Active
or Completing
to Cancelling
when calling cancel
, so it also has no effect on the state of the internal Job
since this transition happens atomically. If a Job
is in the Cancelling
or Cancelled
state than any subsequent calls to cancel
will be ignored.
wait children
+-----+ start +--------+ complete +-------------+ finish +-----------+
| New | -----> | Active | ---------> | Completing | -------> | Completed |
+-----+ +--------+ +-------------+ +-----------+
| cancel / fail |
| +----------------+
| |
V V
+------------+ finish +-----------+
| Cancelling | --------------------------------> | Cancelled |
+------------+ +-----------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With