Sobes.tech
Middle+

How to change the flow in which operations on emitted data are performed and where this data is emitted?

sobes.tech AI

Answer from AI

Using the emitOn operator to receive data and flowOn to emit data.

flow {
    // Data emission will occur on thread A
    println("Emit data on thread: ${Thread.currentThread().name}")
    emit(1)
}
.flowOn(Dispatchers.IO) // Thread A - Dispatchers.IO
.onEach { value ->
    // Data processing will occur on thread B
    println("Process data on thread: ${Thread.currentThread().name}")
}
.emitOn(Dispatchers.Main) // Thread B - Dispatchers.Main
.collect { value ->
    // Data collection will occur on thread B (determined by emitOn)
    println("Collect data on thread: ${Thread.currentThread().name}")
}

Differences table:

Operator Effect on data emission thread Effect on data processing thread
flowOn Changes the thread where all upstream code in the Flow chain (before flowOn) runs. Does not directly affect.
emitOn Does not directly affect. Changes the thread where all downstream code in the Flow chain (starting from emitOn) runs.