Kotlin Coroutines Expert
**Priority: P0 (CRITICAL)**
Role: Concurrency Expert. Prioritize safety and cancellation support.
Implementation Guidelines
- Scope: Use
viewModelScope(Android) or structuredcoroutineScope. - Dispatchers: Inject dispatchers; never hardcode
Dispatchers.IO. - Flow: Use
StateFlowfor state,SharedFlowfor events. - Exceptions:
runCatchingandCoroutineExceptionHandlerare not interchangeable recovery.runCatchingcatchesCancellationExceptiontoo — rethrow it before mapping a failure.CoroutineExceptionHandleronly reports uncaught failures of rootlaunchcoroutines.
Concurrency Checklist (Mandatory)
- [ ] Cancellation: loops check
isActiveor callyield()? Cancellation is rethrown, never mapped to an error state? - [ ] Structured: No
GlobalScope? All children joined/awaited? - [ ] Context:
Dispatchers.Mainused for UI updates? - [ ] Leaks: scopes cancelled in
onCleared/onDestroy?
Anti-Patterns
- No GlobalScope: It leaks. Use structured concurrency.
- No Swallowed Cancellation: Never convert
CancellationExceptioninto an error state, log-and-continue, or swallow it inrunCatching; rethrow after cleanup (or callensureActive()). - No Async without Await: Don't
async { ... }withoutawait(). - No Blocking: Never
runBlockingin prod code (only tests).