Canceling a Coroutine
Explore how to cancel Kotlin coroutines properly by using the Job's cancel method and the yield function. Understand coroutine cancellation behavior, differences between cancellable and non-cancellable coroutines, and how suspending functions enable cooperative cancellation for responsive concurrent execution.
We'll cover the following...
If you’re a Java developer, you may already know that stopping a thread is quite complicated.
For example, the Thread.stop() method is deprecated. There’s Thread.interrupt(), but not all threads are checking this flag, not to mention setting a volatile flag, which is often suggested but is very cumbersome.
If we are using a thread pool, we will get Future, which has the cancel(boolean mayInterruptIfRunning) method. In Kotlin, the launch() function returns a job. ...