Skip to content
ArceApps Logo ArceApps
ES

Kotlin Coroutines: The Android Guide

⏱️ 2 min read
Kotlin Coroutines: The Android Guide

🔄 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

  1. Callbacks: Callback Hell (onSuccess, onError nested 5 levels deep).
  2. RxJava: Powerful but steep learning curve and verbose.
  3. 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

  1. GlobalScope: Avoid it. It has no lifecycle and can leak memory.
  2. Catching CancellationException: Don’t catch generic Exception inside a coroutine, or you might break cancellation. Rethrow CancellationException.
  3. Blocking Code: Never call Thread.sleep inside a coroutine. Use delay.

🏁 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
Kotlin October 15, 2025

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.

Read more
Clean Architecture: The Ultimate Guide for Modern Android
Architecture October 15, 2025

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.

Read more
StateFlow vs. SharedFlow: A Practical Guide
Kotlin October 15, 2025

StateFlow vs. SharedFlow: A Practical Guide

When to use which? Hot streams in Kotlin Coroutines. How to prevent event loss and ensure UI consistency.

Read more