Consider the following Kotlin code using flowOn. What will be printed?
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { flow { println("Emitting on thread: ${Thread.currentThread().name}") emit(1) } .flowOn(Dispatchers.Default) .collect { println("Collected $it on thread: ${Thread.currentThread().name}") } }
Remember that flowOn changes the dispatcher of the upstream flow emissions.
The flowOn(Dispatchers.Default) makes the emission happen on the Default dispatcher thread, but the collect happens on the original coroutine context, which is main here.
Choose the correct statement about flowOn in Kotlin Flow.
Think about which part of the flow flowOn affects.
flowOn changes the dispatcher only for the upstream flow emissions, not the downstream collection.
Examine the code below. Why does it throw an exception at runtime?
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { flow { emit(1) } .flowOn(Dispatchers.IO) .collect { delay(1000) println(it) } }
Recall that collect is a suspend function and can call delay.
The code runs fine because collect is a suspend function and can call delay. There is no runtime error.
What will this Kotlin program print?
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { flow { println("Start emitting on: ${Thread.currentThread().name}") emit(1) } .flowOn(Dispatchers.IO) .map { println("Mapping $it on: ${Thread.currentThread().name}") it * 2 } .flowOn(Dispatchers.Default) .collect { println("Collected $it on: ${Thread.currentThread().name}") } }
Remember each flowOn affects upstream operators only.
The first flowOn(Dispatchers.IO) moves emission to IO thread. The second flowOn(Dispatchers.Default) moves the map operator upstream to Default dispatcher. Collection happens on main.
Given a flow chain with multiple operators and flowOn calls, which statement is true?
Think about the direction of data flow and which operators flowOn affects.
flowOn changes the dispatcher of all upstream operators before it in the flow chain, not downstream.