Answer
Coroutine Scopes define the lifecycle of coroutines. They control when coroutines should start, stop, or be cancelled.
Common Scopes
1. GlobalScope
- Lifecycle: Lives as long as the application process.
- Use Case: Rarely used. Good for top-level background processes that should not be cancelled with any specific component.
- Risk: Can lead to memory leaks if not managed carefully.
2. MainScope
- Lifecycle: Tied to the UI (Main) thread.
- Use Case: UI operations in standard Kotlin/Java applications (outside Android Architecture Components).
- Behavior: Uses
Dispatchers.Main by default.
3. viewModelScope (Android specific)
- Lifecycle: Tied to the
ViewModel.
- Use Case: Launching coroutines that should be cancelled when the ViewModel is cleared.
- Behavior: Automatically cancels all child coroutines when
onCleared() is called.
4. lifecycleScope (Android specific)
- Lifecycle: Tied to the
LifecycleOwner (Activity/Fragment).
- Use Case: UI updates that should stop when the Activity/Fragment is destroyed.
- Behavior: Automatically cancelled when the Lifecycle is destroyed.
5. CoroutineScope (Custom)
- Lifecycle: Defined by the developer.
- Use Case: When you need a scope with a specific lifecycle not covered by standard scopes.
- Example:
val scope = CoroutineScope(Dispatchers.IO + Job())
scope.launch { ... }
scope.cancel()
Sharing helps the Android community grow ๐