0
0
Kotlinprogramming~3 mins

Why Dispatchers.Main, IO, Default behavior in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app never froze again, no matter how much data it handled?

The Scenario

Imagine you are building an app that fetches data from the internet and updates the screen. If you try to do everything on the same thread, the app freezes and becomes unresponsive.

The Problem

Doing all tasks manually on one thread is slow and risky. The app can freeze, crash, or behave unpredictably because heavy work blocks the screen updates.

The Solution

Using Dispatchers like Main, IO, and Default lets you run tasks on the right threads automatically. This keeps the app smooth and fast without freezing.

Before vs After
Before
fun fetchData() {
  val data = fetchFromNetwork() // blocks UI
  updateUI(data)
}
After
fun fetchData() = CoroutineScope(Dispatchers.IO).launch {
  val data = fetchFromNetwork()
  withContext(Dispatchers.Main) {
    updateUI(data)
  }
}
What It Enables

You can write simple code that runs heavy tasks in the background and updates the UI smoothly without freezing.

Real Life Example

When you scroll a social media feed, images load in the background (IO dispatcher) while the screen stays responsive (Main dispatcher).

Key Takeaways

Manual threading causes app freezes and bugs.

Dispatchers manage where code runs for best performance.

Main is for UI, IO for network/disk, Default for CPU work.