Wow, I looked at the official coroutine guide and you are right, it doesn’t go into much detail about how to start coroutines in a real-world situation.
launch
and async
are extension methods on CoroutineScope
. So you need to create a scope with either CoroutineScope()
(which uses the default dispatcher) or MainScope()
(which uses the main dispatcher). If you are programming in Android then activities, fragments, and view models will create their own scopes you can use.
You create the scope at the beginning of your coroutines’ lifecycle, and you cancel()
it when the lifecycle is over.