suspend functions, scopes, dispatchers, and Flow—replace callbacks and LiveData with coroutines.
Coroutines are Kotlin’s way to handle async work without blocking. Here’s how to use them on Android.
Kotlin coroutines and async
Basics
suspend — Functions that can pause without blocking a thread. Call them from another suspend function or a coroutine builder (launch, async).
Scope — CoroutineScope ties work to a lifecycle. Use viewModelScope in ViewModels and lifecycleScope in activities/fragments so coroutines cancel when the scope is cancelled.
Dispatchers — Dispatchers.Main for UI; Dispatchers.IO for disk/network; Dispatchers.Default for CPU work. Switch with withContext.
Flow — Cold streams of values. Use for database queries, pagination, or any stream. Collect in a coroutine; use stateIn or sharedIn to expose to Compose or View.
Coroutine usage (Android projects):
Async approach in Android (%)
ViewModel + Flow
Expose UI state as StateFlow or State from a ViewModel. Use flow { } or callbackFlow for one-off or callback-based sources. Cancel on clear() so you don’t leak.
Coroutines explained:
Takeaway
Use coroutines for all async work on Android. Stick to viewModelScope and lifecycleScope; use withContext to switch threads. Prefer Flow over LiveData for new code.