Challenge - 5 Problems
Flow Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Flow code?
Consider this Kotlin Flow code that emits numbers with delay. What will be printed?
Kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val flow = flow { for (i in 1..3) { delay(100) emit(i) } } flow.collect { value -> println("Received $value") } }
Attempts:
2 left
💡 Hint
Flow emits values sequentially with delay, collect prints each as it arrives.
✗ Incorrect
The flow emits numbers 1 to 3 with a delay of 100ms each. The collect function prints each value as it is emitted, so the output is Received 1, then 2, then 3 in order.
🧠 Conceptual
intermediate1:30remaining
Why use Flow instead of a simple suspend function returning a list?
Which reason best explains why Kotlin Flow is preferred for asynchronous sequences over a suspend function that returns a full list?
Attempts:
2 left
💡 Hint
Think about how data arrives and is processed over time.
✗ Incorrect
Flow allows emitting values one at a time asynchronously, so consumers can start processing early without waiting for the entire list. Suspend functions returning lists wait until all data is ready.
🔧 Debug
advanced2:00remaining
What error does this Flow code produce?
This Kotlin code tries to collect from a Flow but crashes. What error is thrown?
Kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val flow = flow { emit(1) throw RuntimeException("Oops") } flow.collect { value -> println(value) } }
Attempts:
2 left
💡 Hint
Look at what happens after emitting the first value.
✗ Incorrect
The flow emits 1, then throws a RuntimeException. The collect call propagates this exception, causing the program to crash with that error.
📝 Syntax
advanced1:30remaining
Which option correctly creates a Flow emitting squares of 1 to 3?
Choose the Kotlin code snippet that correctly creates a Flow emitting 1, 4, 9.
Attempts:
2 left
💡 Hint
Remember Kotlin syntax for loops and emit inside flow builder.
✗ Incorrect
Option B uses correct Kotlin syntax: a for loop inside flow builder with emit calls. Other options have syntax errors or misuse map.
🚀 Application
expert2:30remaining
How many items does this Flow emit before cancellation?
Given this Kotlin Flow code with cancellation, how many values are printed before the program stops?
Kotlin
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val flow = flow { var i = 1 while (true) { emit(i++) delay(50) } } val job = launch { flow.collect { value -> println(value) if (value == 3) cancel() } } job.join() }
Attempts:
2 left
💡 Hint
Look when cancellation happens inside collect.
✗ Incorrect
The flow emits values starting from 1. When value 3 is received, the coroutine cancels itself, so exactly 3 values are printed.