🚀 Enrollments Open for Jetpack Compose Cohort 2 — 7 Days of Live Learning to Build Modern Android UIs 💚Join Now
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 ```

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

Accelerate Your Growth

Don't just learn concepts in isolation. Build production-ready Android apps with expert guidance.

Live Interactive Sessions
Code Reviews & Feedback
Real-world Projects
Career Guidance

Limited seats available for next cohort