Bird
Raised Fist0
Kotlinprogramming~20 mins

Flow builder and collect in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flow Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Kotlin Flow code?

Consider the following Kotlin code using flow builder and collect. What will be printed?

Kotlin
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)
    }
}
A
1
2
3
BCompilation error
C
2
4
6
D
3
6
9
Attempts:
2 left
💡 Hint

Remember that collect receives each emitted value and you can transform it inside the lambda.

❓ Predict Output
intermediate
2:00remaining
What does this Flow builder code print?

Analyze this Kotlin code snippet using flow and collect. What is the output?

Kotlin
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)
    }
}
ACompilation error
B
1
2
3
C
2
D
1
3
Attempts:
2 left
💡 Hint

Look at the return@collect statement inside the collect lambda.

❓ Predict Output
advanced
2:00remaining
What is the output of this Flow with delay and collect?

Consider this Kotlin code using flow with delays. What will be printed?

Kotlin
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)
    }
}
A
1
2
3
B
3
2
1
C
1
1
1
DCompilation error
Attempts:
2 left
💡 Hint

The delay suspends the flow emission but does not change the order.

❓ Predict Output
advanced
2:00remaining
What error does this Flow code produce?

What error will this Kotlin code produce when run?

Kotlin
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)
    }
}
ANo output, program runs normally
BIllegalStateException: Error in flow
CNullPointerException
DCompilation error
Attempts:
2 left
💡 Hint

Exceptions thrown inside flow builder propagate to the collector.

🧠 Conceptual
expert
2:00remaining
How many items are collected from this Flow?

Given this Kotlin Flow code, how many items will be collected and printed?

Kotlin
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")
}
A3 items
B5 items
C0 items
DCompilation error
Attempts:
2 left
💡 Hint

The break statement terminates the loop after emitting 3.

Practice

(1/5)
1. What is the primary purpose of the flow {} builder in Kotlin?
easy
A. To create a stream of values that can be emitted over time
B. To immediately execute a block of code and return a single value
C. To collect values from a list synchronously
D. To define a suspend function without any emissions

Solution

  1. Step 1: Understand the role of flow {}

    The flow {} builder creates a stream that can emit multiple values asynchronously over time.
  2. Step 2: Compare with other options

    Options B, C, and D describe synchronous or non-stream behaviors, which do not match flow {} usage.
  3. Final Answer:

    To create a stream of values that can be emitted over time -> Option A
  4. Quick Check:

    Flow builder = stream of values [OK]
Hint: Remember: flow builds streams, not single immediate values [OK]
Common Mistakes:
  • Confusing flow with suspend functions returning single values
  • Thinking flow collects values instead of emitting them
  • Assuming flow is synchronous
2. Which of the following is the correct syntax to collect values from a flow named myFlow inside a suspend function?
easy
A. myFlow.collect(value -> println(value))
B. myFlow.collect { println(value) }
C. myFlow.collect { value -> println(value) }
D. myFlow.collect { value => println(value) }

Solution

  1. Step 1: Identify correct lambda syntax in Kotlin

    Kotlin uses curly braces with parameter and arrow: { param -> action }.
  2. Step 2: Match syntax with options

    myFlow.collect { value -> println(value) } correctly uses { value -> println(value) }. Options A lacks braces, B misses parameter declaration (value undefined), D uses wrong arrow symbol (=>).
  3. Final Answer:

    myFlow.collect { value -> println(value) } -> Option C
  4. Quick Check:

    Correct lambda syntax = myFlow.collect { value -> println(value) } [OK]
Hint: Use { param -> action } syntax for Kotlin lambdas [OK]
Common Mistakes:
  • Omitting lambda parameter name
  • Using Java-style arrows (->) incorrectly
  • Using parentheses instead of curly braces
3. What will be the output of the following Kotlin code?
import kotlinx.coroutines.flow.*
suspend fun main() {
    val numbers = flow {
        emit(1)
        emit(2)
        emit(3)
    }
    numbers.collect { println(it * 2) }
}
medium
A. 1 2 3
B. 2 4 6
C. 3 6 9
D. Compilation error

Solution

  1. Step 1: Analyze emitted values

    The flow emits 1, 2, and 3 sequentially.
  2. Step 2: Understand the collect block

    Each emitted value is multiplied by 2 and printed, so outputs are 2, 4, and 6.
  3. Final Answer:

    2 4 6 -> Option B
  4. Quick Check:

    Emitted values * 2 = 2,4,6 [OK]
Hint: Multiply emitted values inside collect to get output [OK]
Common Mistakes:
  • Printing original values without multiplication
  • Expecting a list output instead of separate prints
  • Assuming compilation error due to missing coroutine context
4. Identify the error in this Kotlin flow code snippet:
val flow = flow {
    emit(1)
    emit(2)
}
flow.collect { println(it) }
medium
A. collect should be called with parentheses
B. Incorrect flow builder syntax
C. emit cannot be called inside flow builder
D. Missing suspend modifier on the function calling collect

Solution

  1. Step 1: Check flow and collect usage

    The flow builder and emit calls are correct.
  2. Step 2: Understand collect context

    Collect is a suspend function and must be called from a suspend function or coroutine scope. Calling it directly without suspend context causes error.
  3. Final Answer:

    Missing suspend modifier on the function calling collect -> Option D
  4. Quick Check:

    collect requires suspend context [OK]
Hint: Remember: collect is suspend, needs suspend function or coroutine [OK]
Common Mistakes:
  • Trying to call collect outside suspend or coroutine
  • Confusing emit usage inside flow
  • Thinking collect syntax is wrong
5. You want to create a flow that emits only even numbers from 1 to 5 and then collect and print them. Which code snippet correctly achieves this?
hard
A. val flow = flow { for (i in 1..5) { if (i % 2 == 0) emit(i) } } suspend fun main() { flow.collect { println(it) } }
B. val flow = flowOf(1, 2, 3, 4, 5).filter { it % 2 == 0 } fun main() { flow.collect { println(it) } }
C. val flow = flow { emit(2) emit(4) } flow.collect { println(it) }
D. val flow = flow { for (i in 1..5) emit(i) } flow.collect { if (it % 2 == 0) println(it) }

Solution

  1. Step 1: Check flow emission of even numbers

    val flow = flow { for (i in 1..5) { if (i % 2 == 0) emit(i) } } suspend fun main() { flow.collect { println(it) } } emits only even numbers inside the flow builder using a for loop and condition.
  2. Step 2: Verify collection and printing

    val flow = flow { for (i in 1..5) { if (i % 2 == 0) emit(i) } } suspend fun main() { flow.collect { println(it) } } collects the flow inside a suspend function and prints each emitted value correctly.
  3. Final Answer:

    val flow = flow { for (i in 1..5) { if (i % 2 == 0) emit(i) } } suspend fun main() { flow.collect { println(it) } } -> Option A
  4. Quick Check:

    Emit filtered values inside flow, collect in suspend [OK]
Hint: Filter inside flow builder to emit only needed values [OK]
Common Mistakes:
  • Calling collect outside suspend function
  • Filtering after emitting all values instead of inside flow
  • Not using suspend function for collect
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard