Challenge - 5 Problems
StateFlow Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What happens when StateFlow value changes?
Consider a StateFlow holding an integer count. When the count updates, what will the UI displaying this count do?
Android Kotlin
val countFlow = MutableStateFlow(0) // UI collects countFlow and shows count countFlow.value = 5
Attempts:
2 left
💡 Hint
StateFlow emits new values to collectors automatically.
✗ Incorrect
StateFlow is designed to emit updates to its collectors whenever its value changes, so the UI observing it will update automatically.
❓ lifecycle
intermediate2:00remaining
StateFlow collection and lifecycle
In an Android app, what happens if you collect a StateFlow in a ViewModel but the UI lifecycle is destroyed?
Android Kotlin
val stateFlow = MutableStateFlow("Hello") // UI collects stateFlow in lifecycleScope // UI is destroyed
Attempts:
2 left
💡 Hint
Lifecycle-aware scopes stop coroutines when lifecycle ends.
✗ Incorrect
Collecting StateFlow in lifecycleScope ensures collection stops when the UI lifecycle is destroyed, preventing leaks.
📝 Syntax
advanced2:00remaining
Correct syntax to expose StateFlow from ViewModel
Which option correctly exposes a read-only StateFlow from a ViewModel?
Android Kotlin
private val _state = MutableStateFlow(0)
// expose stateAttempts:
2 left
💡 Hint
Expose StateFlow as an interface, not mutable type.
✗ Incorrect
Option C exposes _state as a read-only StateFlow, hiding mutability from outside.
🔧 Debug
advanced2:00remaining
Why does UI not update when StateFlow value changes?
Given this code, why does the UI not update when _count.value changes?
class MyViewModel : ViewModel() {
private val _count = MutableStateFlow(0)
val count: StateFlow = _count
fun increment() {
_count.value += 1
}
}
// UI collects count but never updates
Attempts:
2 left
💡 Hint
StateFlow emits only when collected in a coroutine.
✗ Incorrect
If UI does not collect StateFlow in a coroutine, it won't receive updates and won't update UI.
🧠 Conceptual
expert2:00remaining
StateFlow vs SharedFlow for UI state
Which statement best explains why StateFlow is preferred over SharedFlow for holding UI state?
Attempts:
2 left
💡 Hint
Think about replay behavior and state retention.
✗ Incorrect
StateFlow always keeps the latest value and emits it immediately to new collectors, making it ideal for UI state. SharedFlow requires configuration to replay values.