0Pricing
Kotlin Academy · Lesson

flowOn and buffer: Context and Backpressure

Change emission context with flowOn and buffer emissions for backpressure.

Flow Context

By default, a flow runs in the context of the coroutine that calls collect. The dispatcher of the producer and consumer are the same unless you change it.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    flow {
        println("emit on: ${Thread.currentThread().name}")
        emit(1)
    }.collect {
        println("collect on: ${Thread.currentThread().name}")
    }
}

flowOn Changes Upstream Context

flowOn(dispatcher) runs the upstream flow (everything above it in the chain) on the specified dispatcher, while collection stays on the caller's dispatcher.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    flow {
        println("emit: ${Thread.currentThread().name}")
        emit(1)
    }.map {
        println("map: ${Thread.currentThread().name}")
        it * 2
    }.flowOn(Dispatchers.Default)  // above runs on Default
    .collect {
        println("collect: ${Thread.currentThread().name}")
    }
}

All lessons in this course

  1. Flow Operators: map, filter, transform, and take
  2. catch and onCompletion: Error Handling in Flow
  3. combine and zip: Merging Multiple Flows
  4. flowOn and buffer: Context and Backpressure
← Back to Kotlin Academy