Discover how StateFlow and SharedFlow make your app's data updates smooth and bug-free!
Why StateFlow and SharedFlow in Android Kotlin? - Purpose & Use Cases
Imagine you are building an app where multiple parts need to know when data changes, like a shopping cart updating the item count in different screens.
Without a proper way to share these updates, you might try to manually pass data around or use callbacks everywhere.
Manually passing data or using callbacks can get messy fast. It's easy to miss updates, cause bugs, or write repetitive code.
Also, managing the timing of updates and ensuring all parts get the latest info is tricky and error-prone.
StateFlow and SharedFlow provide a clean, reactive way to share data updates across your app.
StateFlow holds the latest value and emits it to new subscribers automatically, perfect for UI state.
SharedFlow broadcasts events to multiple subscribers without holding a value, great for one-time events.
fun updateCart() {
cartCount++
notifyAllScreens(cartCount)
}val cartState = MutableStateFlow(0) fun addItem() { cartState.value = cartState.value + 1 }
It enables smooth, reliable communication of data changes across your app without tangled code or missed updates.
When a user adds an item to their cart, StateFlow instantly updates the cart icon count on every screen without extra code.
Manual data sharing is slow and error-prone.
StateFlow and SharedFlow simplify reactive data updates.
They help keep your app UI in sync effortlessly.
Practice
StateFlow and SharedFlow in Kotlin?Solution
Step 1: Understand
StateFlowbehaviorStateFlowalways holds the latest emitted value and replays it to new collectors.Step 2: Understand
SharedFlowbehaviorSharedFlowemits events but does not hold or replay the latest value by default.Final Answer:
StateFlowholds the latest value,SharedFlowdoes not hold any value. -> Option BQuick Check:
StateFlow holds state, SharedFlow emits events [OK]
- Thinking SharedFlow holds the latest value like StateFlow
- Confusing event emission with state holding
- Assuming both behave the same way
StateFlow with an initial value of 0?Solution
Step 1: Identify correct constructor for StateFlow
MutableStateFlowrequires an initial value and is created withMutableStateFlow(initialValue).Step 2: Check other options
MutableSharedFlowdoes not take an initial value;StateFlowis an interface and cannot be instantiated directly.Final Answer:
val stateFlow = MutableStateFlow(0) -> Option CQuick Check:
MutableStateFlow needs initial value [OK]
- Trying to instantiate StateFlow interface directly
- Using SharedFlow constructor for StateFlow
- Passing initial value to MutableSharedFlow
val stateFlow = MutableStateFlow(10) stateFlow.value = 20 println(stateFlow.value)
Solution
Step 1: Understand MutableStateFlow value assignment
AssigningstateFlow.value = 20updates the current value held by the StateFlow.Step 2: Print the current value
println(stateFlow.value)prints the latest value, which is 20.Final Answer:
20 -> Option DQuick Check:
StateFlow.value reflects latest assigned value [OK]
- Thinking initial value 10 will print instead of updated 20
- Confusing StateFlow with SharedFlow behavior
- Expecting null or error due to reassignment
SharedFlow?
val sharedFlow = MutableSharedFlow<Int>() sharedFlow.value = 5
Solution
Step 1: Check
SharedFlowpropertiesSharedFlowdoes not hold state and has novalueproperty to assign.Step 2: Understand how to emit values
Values are emitted usingemit()ortryEmit()functions, not by assigningvalue.Final Answer:
SharedFlowdoes not have avalueproperty to assign. -> Option AQuick Check:
SharedFlow emits events, no value property [OK]
- Trying to assign value property on SharedFlow
- Confusing SharedFlow with StateFlow
- Assuming SharedFlow holds state like StateFlow
SharedFlow that replays the last 3 emitted values to new collectors. Which configuration is correct?Solution
Step 1: Understand
Thereplayparameter in SharedFlowreplayparameter defines how many past values are replayed to new collectors.Step 2: Check options for replaying last 3 values
Settingreplay = 3inMutableSharedFlowcorrectly configures this behavior.Final Answer:
val sharedFlow = MutableSharedFlow<Int>(replay = 3) -> Option AQuick Check:
Replay count sets how many past events are replayed [OK]
- Confusing bufferSize with replay
- Using StateFlow instead of SharedFlow for replay
- Setting replay to 0 expecting replay behavior
Ready to prove it?
Pass the test and this pattern moves unknown
