🚀 Enrollments Open for Jetpack Compose Cohort 2 — 7 Days of Live Learning to Build Modern Android UIs 💚Join Now
KotlinIntermediate4 min
What happens if we call .cancel() from a coroutine scope?

Answer

Calling `.cancel()` on a `CoroutineScope`:

  1. Cancels all active child coroutines launched within that scope.
  2. Cancels the scope itself.
  3. Irreversible: Once a scope is cancelled, you cannot launch new coroutines in it. Any attempt to `launch` or `async` in a cancelled scope will throw a `CancellationException` (or simply be ignored depending on implementation, but effectively the job is dead).

Best Practice

  • Only cancel a scope when the component associated with it is being destroyed (e.g., `onDestroy` in Activity).
  • If you want to cancel children but keep the scope alive (e.g., user cancels an operation but stays on the screen), cancel the Job of the specific coroutine or use `coroutineContext.cancelChildren()`.

```kotlin // Cancel children but keep scope alive scope.coroutineContext.cancelChildren() ```

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