Cancellation: Stopping the Unstoppable

Learn how cancellation happens without a suspension point and how to use suspendCancellableCoroutine.

Because cancellation happens on suspension points, it won’t happen without a suspension point. To simulate such a situation, we could use Thread.sleep instead of delay. This is a terrible practice, so please don’t do this in any real-life projects. We’re just trying to simulate a case in which we are using our coroutines extensively but not suspending them. In practice, such a situation might happen if we have some complex calculations, like neural network learning (yes, we also use coroutines for such cases to simplify processing parallelization), or when we need to do some blocking calls (for instance, reading files).

The example below presents a coroutine that cannot be canceled because there is no suspension point inside it (we use Thread.sleep instead of delay). The execution needs over three minutes, even though it should be canceled after one second.

Get hands-on with 1200+ tech skills courses.