Questions
KotlinIntermediate4 min
What happens if we call .cancel() from a coroutine scope?
Answer
Calling `.cancel()` on a `CoroutineScope`:
- Cancels all active child coroutines launched within that scope.
- Cancels the scope itself.
- 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() ```
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 💚