Kotlin Coroutines: The Android Guide
Table of Contents
🔄 The Async Problem
Android apps are single-threaded by default (Main Thread). Long operations (Network, DB) block the UI, causing ANRs (Application Not Responding).
Callbacks vs. RxJava vs. Coroutines
- Callbacks: Callback Hell (
onSuccess,onErrornested 5 levels deep). - RxJava: Powerful but steep learning curve and verbose.
- Coroutines: Write async code sequentially. Built-in language support.
🧵 Dispatchers
Where does the code run?
- Dispatchers.Main: UI Thread (Updating views).
- Dispatchers.IO: Network, Disk (Reading files, API calls).
- Dispatchers.Default: CPU Intensive (Parsing JSON, sorting lists).
Best Practice: Inject Dispatchers
Don’t hardcode Dispatchers.IO. Inject them to make testing easier.
class UserRepository(
private val ioDispatcher: CoroutineDispatcher
) {
suspend fun getUser() = withContext(ioDispatcher) { ... }
}
🏗️ Structured Concurrency
Coroutines are launched in a Scope. When the scope dies, all coroutines are cancelled.
ViewModelScope
Tied to ViewModel lifecycle. Cleared when ViewModel is cleared.
viewModelScope.launch {
// Automatically cancelled if user leaves screen
repository.getData()
}
LifecycleScope
Tied to Fragment/Activity lifecycle.
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
// Collect flows safely
}
}
⚠️ Common Pitfalls
- GlobalScope: Avoid it. It has no lifecycle and can leak memory.
- Catching CancellationException: Don’t catch generic
Exceptioninside a coroutine, or you might break cancellation. RethrowCancellationException. - Blocking Code: Never call
Thread.sleepinside a coroutine. Usedelay.
🏁 Conclusion
Coroutines simplify async code dramatically. By understanding scopes and dispatchers, you can write safe, efficient, and readable concurrent code.
You might also be interested in
Advanced Kotlin Flow: Operators and Patterns
Level up with Kotlin Flow. Master operators like combine, zip, flatMapLatest, and learn to handle complex reactive streams in Android.
Clean Architecture: The Ultimate Guide for Modern Android
Demystifying Clean Architecture: A deep dive into layers, dependencies, and data flow to build indestructible Android apps.
StateFlow vs. SharedFlow: A Practical Guide
When to use which? Hot streams in Kotlin Coroutines. How to prevent event loss and ensure UI consistency.