Structured concurrency
Structured concurrency is a concept in Kotlin that ensures the orderly execution and completion of coroutines. It ties the life cycle of coroutines to the scope they are launched in, making it easier to manage and control them. Under structured concurrency, when a coroutine scope is canceled or completes its execution, all coroutines launched within that scope are also canceled or completed. This approach simplifies the handling of concurrent operations, preventing resource leaks and ensuring that coroutines don’t run longer than necessary.
Let’s look at an example. It is a very common practice to spawn coroutines from inside another coroutine.
The first rule of structured concurrency is that the parent coroutine should always wait for all its children to complete. This prevents resource leaks, which are very common in languages that don’t have the structured concurrency concept.
This means that if we look at the following code...