0
0
Android Kotlinmobile~20 mins

Flow basics in Android Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Flow Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ui_behavior
intermediate
2:00remaining
What is the output of this Flow collection?
Consider this Kotlin Flow code that emits numbers and collects them. What will be printed?
Android 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)
  }
}
A1\n2\n3
B3\n2\n1
C1 2 3 on one line
DNo output, code does not compile
Attempts:
2 left
💡 Hint
Remember that Flow emits values in the order they are emitted inside the flow builder.
🧠 Conceptual
intermediate
1:30remaining
What does the 'flowOn' operator do in Kotlin Flow?
Choose the correct description of the 'flowOn' operator in Kotlin Flow.
ACancels the flow immediately
BChanges the context where the flow is collected
CChanges the context where the flow is emitted
DBuffers the flow emissions
Attempts:
2 left
💡 Hint
Think about where the code inside the flow builder runs.
lifecycle
advanced
2:00remaining
What happens if you collect a Flow multiple times?
Given a cold Flow in Kotlin, what is the behavior when you collect it multiple times?
AThe flow starts emitting from the beginning each time it is collected
BThe flow emits only once and shares the result with all collectors
CThe flow caches the first emission and replays it to new collectors
DThe flow throws an exception on the second collection
Attempts:
2 left
💡 Hint
Cold flows start fresh for each collector.
📝 Syntax
advanced
2:00remaining
What error does this Flow code produce?
Analyze this Kotlin Flow code snippet. What error will it cause?
Android Kotlin
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
  val flow = flow {
    emit(1)
    emit(2)
    emit(3)
  }
  flow.collect { value ->
    if (value == 2) throw Exception("Error at 2")
    println(value)
  }
}
ANo error, prints 1 2 3
BException with message 'Error at 2' is thrown during collection
CCompilation error due to throw inside collect
DRuntime error: NullPointerException
Attempts:
2 left
💡 Hint
Throwing inside collect will propagate the exception.
navigation
expert
2:30remaining
How to cancel a Flow collection properly in Android?
In an Android app using Kotlin Flow, which approach correctly cancels the flow collection when the lifecycle owner is destroyed?
AUse runBlocking { flow.collect { ... } } in the main thread
BUse GlobalScope.launch { flow.collect { ... } } without cancellation
CCollect flow without any coroutine scope
DUse lifecycleScope.launch { flow.collect { ... } } and rely on lifecycleScope cancellation
Attempts:
2 left
💡 Hint
Think about lifecycle-aware coroutine scopes in Android.