Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to call `cancel()` more than once on the same Kotlin coroutine?

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!

like image 543
gfrung4 Avatar asked Sep 20 '25 04:09

gfrung4


1 Answers

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 |
             +------------+                                   +-----------+
like image 55
nomisRev Avatar answered Sep 23 '25 11:09

nomisRev