0
0
Kotlinprogramming~3 mins

Why FlowOn for changing dispatcher in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple keyword can save your app from freezing and crashing!

The Scenario

Imagine you have a task that fetches data from the internet and then updates the user interface. Doing both on the same thread can freeze your app, making it unresponsive and frustrating for users.

The Problem

Manually switching threads for each step is tricky and error-prone. You might forget to switch back to the main thread for UI updates or accidentally block the UI thread, causing crashes or lag.

The Solution

Using flowOn lets you easily tell Kotlin where to run parts of your data stream. It cleanly separates background work from UI updates without messy thread management.

Before vs After
Before
val data = fetchData()
updateUI(data) // both run on main thread, causing lag
After
flow {
  emit(fetchData())
}.flowOn(Dispatchers.IO)
 .collect { data -> updateUI(data) }
What It Enables

You can write smooth, responsive apps by effortlessly moving heavy work off the main thread and keeping UI updates fast and safe.

Real Life Example

When loading images from the internet, flowOn runs the download in the background, then updates the screen on the main thread without freezing the app.

Key Takeaways

Manual thread switching is hard and risky.

flowOn cleanly changes where flows run.

This keeps apps responsive and code simple.