0
0
Kotlinprogramming~5 mins

Flow context preservation in Kotlin

Choose your learning style9 modes available
Introduction

Flow context preservation helps keep the same environment or settings when running code that works with streams of data. It makes sure the code runs smoothly without losing important information.

When you want to keep the same thread or dispatcher while processing data streams.
When you need to maintain user session or request context across asynchronous operations.
When you want to avoid switching threads unnecessarily in reactive programming.
When you want to ensure logging or debugging information stays consistent during flow operations.
Syntax
Kotlin
flowOn(context: CoroutineContext): Flow<T>

flowOn changes the context where the flow runs.

Use it to switch threads or dispatchers safely inside a flow.

Examples
This runs the flow emissions on the IO dispatcher thread.
Kotlin
flow {
    emit(1)
    emit(2)
}.flowOn(Dispatchers.IO)
Runs the computeValue function on the Default dispatcher for CPU work.
Kotlin
flow {
    emit(computeValue())
}.flowOn(Dispatchers.Default)
Sample Program

This program creates a flow that emits two numbers. The flow runs on the IO dispatcher thread, but collection happens on the main thread. It prints thread names to show context preservation.

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

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

    flow.collect { value ->
        println("Collected $value on: ${Thread.currentThread().name}")
    }
}
OutputSuccess
Important Notes

flowOn only affects upstream operations before it, not downstream collectors.

Use flowOn to avoid blocking the main thread during heavy work.

Summary

Flow context preservation keeps the execution environment consistent.

Use flowOn to switch threads safely inside flows.

This helps write efficient and responsive asynchronous code.