Questions
KotlinIntermediate4 min
What are the different Coroutine Scopes?
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: ```kotlin val scope = CoroutineScope(Dispatchers.IO + Job()) scope.launch { ... } scope.cancel() // Must be cancelled manually ```
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚