Cancellations and Timeouts

Coroutines can be cancelled, which will stop the code within the coroutine from further execution. Coroutine cancellations aren’t related to the thread terminations that we’re used to in Java. Cancellations are lightweight and have effect across the hierarchy of coroutines that share context.

Both the Job object, which is returned by launch(), and the Deferred<T> object, which is returned by async(), have a cancel() and a cancelAndJoin() method. We can use these methods to explicitly cancel a coroutine, but there’s a catch. A coroutine is cancelled only if it is currently in a suspension point. If a coroutine is busy executing code, it won’t receive the cancellation notice and may not bail out. Let’s discuss this further ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.