Consider the following Kotlin code using flow builder and collect. What will be printed?
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { val flow = flow { emit(1) emit(2) emit(3) } flow.collect { value -> println(value * 2) } }
Remember that collect receives each emitted value and you can transform it inside the lambda.
The flow emits 1, 2, and 3. The collect block multiplies each value by 2 before printing, so the output is 2, 4, 6.
Analyze this Kotlin code snippet using flow and collect. What is the output?
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { val flow = flow { for (i in 1..3) { emit(i) } } flow.collect { value -> if (value == 2) return@collect println(value) } }
Look at the return@collect statement inside the collect lambda.
The return@collect skips printing when value is 2, so only 1 and 3 are printed.
Consider this Kotlin code using flow with delays. What will be printed?
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking import kotlinx.coroutines.delay fun main() = runBlocking { val flow = flow { emit(1) delay(100) emit(2) delay(100) emit(3) } flow.collect { value -> println(value) } }
The delay suspends the flow emission but does not change the order.
The flow emits 1, then waits 100ms, emits 2, waits 100ms, then emits 3. The collect prints them in order.
What error will this Kotlin code produce when run?
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { val flow = flow { emit(1) throw IllegalStateException("Error in flow") } flow.collect { value -> println(value) } }
Exceptions thrown inside flow builder propagate to the collector.
The flow emits 1, then throws an IllegalStateException. The exception is propagated and terminates the flow.
Given this Kotlin Flow code, how many items will be collected and printed?
import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { val flow = flow { for (i in 1..5) { emit(i) if (i == 3) break } } var count = 0 flow.collect { println(it) count++ } println("Total collected: $count") }
The break statement terminates the loop after emitting 3.
The for loop emits 1, then 2, then 3 and breaks. Thus, 3 items are collected and printed, and count is 3.