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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access