Conclusion
In this lesson, you learned:
- About scopes and dispatchers in Kotlin coroutines.
- The scope of a coroutine is a basic way to control the lifetime of the coroutine.
- Scopes form a parent-children hierarchy of coroutines. By default, if a coroutine fails it will cancel all its siblings and the parent. Unless there is a
SupervisorJobin the context of some of the scopes in the hierarchy. - It’s better to use the predefined scopes bound to the lifecycle of the Android entities.
- If you create your own scope, don’t forget to cancel it manually to avoid bugs.
- The dispatcher is a mechanism that determines which thread the coroutine runs on. Choose the dispatcher according to the task you want to perform. Use the
Defaultfor CPU-bound tasks and theIOfor network and disk requests. TheMaindispatcher is for tasks that update the user interface. Keep in mind you can switch the dispatcher in the coroutine using thewithContext()function.
In the next lesson, you’ll learn about returning values from coroutines.