Can you list the types of scope used in coroutines?
sobes.tech AI
Answer from AI
In Kotlin, coroutines use different scopes (CoroutineScope) that define the lifecycle and execution context of the coroutine. The main types of scopes are:
-
GlobalScope — a global scope where coroutines live as long as the application is running. Used for tasks that should run independently of component lifecycles.
-
CoroutineScope associated with a component's lifecycle — for example, in Android, this is
lifecycleScopeorviewModelScope. Coroutines are automatically canceled when the component (Activity, ViewModel) is destroyed, preventing memory leaks. -
Custom CoroutineScope — you can create your own scopes with specific contexts and dispatchers.
Example of using viewModelScope in Android:
class MyViewModel : ViewModel() {
fun loadData() {
viewModelScope.launch {
// asynchronous data loading
}
}
}
Thus, scopes help manage the lifecycle of coroutines and their execution context.