Cancellation
Learn about cancellation and what triggers it.
We'll cover the following
An essential functionality of Kotlin coroutines is cancellation. It is so vital that some classes and libraries use suspending functions primarily to support cancellation. There is a good reason for this: a suitable cancellation mechanism is worth its weight in gold. It’s worth much more since the code is currently not very heavy (it used to be, when we stored it on punched cards). Just killing a thread is a terrible solution as there should be an opportunity to close connections and free resources. Forcing developers to check if a state is still active frequently isn’t convenient either. The problem of cancellation has waited for a good solution for a very long time, but what Kotlin coroutines offers is surprisingly simple, convenient, and safe. Let’s explore it.
Basic cancellation
The Job
interface has a cancel
method, which allows its cancellation. Calling it triggers the following effects.
Get hands-on with 1400+ tech skills courses.