Last week I asked you about the coroutine scopes in Kotlin and when are they best used?
There are three main coroutine scopes available to use.
- GlobalScope
- LifecycleScope
- ViewModelScope
GlobalScope is a delicate API to use. It can have pretty severe consequences if used improperly. It is not bound to any job and is recommended to be used for coroutines that last the lifetime of the app.
This is a scope provided by the
KTX dependencies. It is a lifecycle aware scope. They are defined to help stop coroutine jobs when a
Lifecycle
is destroyed.
This scope is also provided by the KTX dependencies. This scope is defined for each ViewModel
in an app. Any coroutine launched using this scope will be canceled when the ViewModel
is cleared.
You can also define and manage your own scopes, but if you have to do this I would make sure you are considering why.