15 Structured concurrency

 

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.

15.1 Coroutine scopes establish structure between coroutines

15.1.1 Creating a coroutine scope: The coroutineScope function

15.1.2 Associating coroutine scopes with components: CoroutineScope

15.1.3 The danger of GlobalScope

15.1.4 Coroutine contexts and structured concurrency

15.2 Cancellation

15.2.1 Triggering cancellation

15.2.2 Invoking cancellation automatically after a time limit has been exceeded

15.2.3 Cancellation cascades through all children

15.2.4 Cancelled coroutines throw CancellationExceptions in special places

15.2.5 Cancellation is cooperative

15.2.6 Checking whether a coroutine has been cancelled

15.2.8 Keep cancellation in mind when acquiring resources