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
- Flow Operators: map, filter, transform, and take
- catch and onCompletion: Error Handling in Flow
- combine and zip: Merging Multiple Flows
- flowOn and buffer: Context and Backpressure