0
0
Kotlinprogramming~5 mins

FlowOn for changing dispatcher in Kotlin

Choose your learning style9 modes available
Introduction

FlowOn lets you switch the thread where your flow runs. This helps keep your app fast and smooth by doing work in the right place.

When you want to do heavy work like reading files without freezing the screen.
When you want to update the UI only on the main thread.
When you want to separate background work from UI updates in your app.
When you want to improve app performance by using the right thread for each task.
Syntax
Kotlin
flow {
    emit(someValue)
}.flowOn(dispatcher)

flowOn changes the thread where the flow runs.

You usually use Dispatchers.IO for background work and Dispatchers.Main for UI updates.

Examples
This flow emits a string on the IO thread, good for background tasks.
Kotlin
flow {
    emit("Hello from IO thread")
}.flowOn(Dispatchers.IO)
This flow emits numbers on the Default dispatcher, which is good for CPU work.
Kotlin
flow {
    emit(1)
    emit(2)
}.flowOn(Dispatchers.Default)
Sample Program

This program creates a flow that emits data on the IO thread. The collector runs on the main thread (runBlocking thread). You see which thread runs each part.

Kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val myFlow = flow {
        println("Emitting on thread: ${Thread.currentThread().name}")
        emit("Data 1")
        delay(100)
        emit("Data 2")
    }.flowOn(Dispatchers.IO)

    myFlow.collect {
        println("Collected '$it' on thread: ${Thread.currentThread().name}")
    }
}
OutputSuccess
Important Notes

flowOn only changes the upstream flow's thread, not the collector's thread.

Use flowOn to keep heavy work off the main thread and keep UI smooth.

Summary

flowOn switches the thread where the flow runs.

Use it to run background work on Dispatchers.IO or Dispatchers.Default.

The collector runs on the original coroutine context unless changed.