This chapter covers
- Establishing hierarchies between coroutines via the concept of structured concurrency
- How structured concurrency gives you fine-grained control over execution and cancellation of your code, automatically propagating cancellation across the coroutine hierarchy
- The relationship between the coroutine context and structured concurrency
- Writing code that behaves correctly when cancelled
When you use Kotlin coroutines in the context of real applications, chances are you will be managing a lot of coroutines. Major challenges when working with many concurrent operations are keeping track of the individual tasks that are running, cancelling them when they’re no longer needed, and making sure that errors are handled properly.
Without keeping track of your coroutines, you run the risk of resource leaks and doing unnecessary work. Consider the following example: a user requests a network resource and immediately navigates away to a different screen. If you have no way of keeping track of the (potentially dozens of) coroutines responsible for the network request and postprocessing of the information received, you have no choice but to let them run to completion—even if their result will just be discarded in the end.