🚀 Enrollments Open for 1:1 Mentorship Scheduled as per your availability 💚Book 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.

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

Limited slots available each month

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow 💚