Kotlin coroutines for async operations

2263
0

Kotlin coroutines provide structured concurrency for asynchronous programming. I use suspend functions to mark async code, and launch or async to start coroutines. viewModelScope and lifecycleScope tie coroutines to component lifecycles, cancelling automatically. Dispatchers control execution context—Dispatchers.IO for network/disk, Dispatchers.Main for UI updates, Dispatchers.Default for CPU work. withContext switches dispatchers. async/await enables parallel execution with awaitAll(). Flow provides reactive streams with operators like map, filter, and collect. StateFlow and SharedFlow share state across coroutines. Error handling uses try/catch or CoroutineExceptionHandler. Coroutines replace callbacks and RxJava with cleaner, sequential code.