June 2018
Intermediate to advanced
310 pages
6h 32m
English
If you are a Java developer, you may 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 your own volatile flag, which is often suggested but is very cumbersome.
If you're using a thread pool, you'll get Future, which has the cancel(boolean mayInterruptIfRunning) method. In Kotlin, the launch() function returns a job.
This job can be canceled. The same rules as the previous example apply, though. If your coroutine never calls another suspend method or yields, it will disregard cancel().
To demonstrate that, we'll create one nice coroutine that yields once in a while:
val Read now
Unlock full access