What problem does it solve?
Android apps often struggle with lifecycle-unsafe coroutine usage, leading to leaks, crashes, or unresponsive UI. This guide delivers practical patterns to write lifecycle-aware, testable coroutine code using viewModelScope, proper Dispatchers, Flow in Compose, and robust error handling.
Core Features & Use Cases
- ViewModel-scoped coroutines with viewModelScope for lifecycle safety across config changes.
- Dispatcher guidance for Main, IO, and Default to optimize UI responsiveness and background work.
- Flow collection in Compose with collectAsStateWithLifecycle for safe UI state exposure.
- LaunchedEffect and side-effect handling for one-time or key-based actions.
- Managing long-running jobs with cancellation and proper cleanup.
- Testing strategies with TestDispatcher, runTest, and Turbine for Flow emissions.
- Anti-patterns to avoid, including GlobalScope, blocking Main thread, and unchecked exceptions.
Quick Start
Refactor a sample Android ViewModel to use viewModelScope, the correct Dispatchers, and collectAsStateWithLifecycle for Compose to improve lifecycle safety and testability.