Questions
KotlinIntermediate4 min
Difference between Flow/SharedFlow/StateFlow and elaborate it.
Answer
These are Kotlin's stream APIs for handling asynchronous data streams.
1. Flow (Cold Stream)
- Behavior: Code inside a flow builder does not run until the flow is collected.
- State: Stateless. Does not hold the last value.
- Subscribers: One-to-one. Each collector triggers a new execution of the flow block.
- Use Case: Fetching data from a database, network requests where you want fresh data for each observer.
2. StateFlow (Hot Stream)
- Behavior: Emits updates to collectors. Always has an initial value.
- State: Stateful. Holds the current value.
- Subscribers: One-to-many (Multicast). Multiple collectors share the same stream.
- Replay: Replays the latest value to new collectors immediately.
- Use Case: UI State management (replacement for LiveData).
3. SharedFlow (Hot Stream)
- Behavior: Highly configurable hot stream. Can emit values without an initial value.
- State: Can be stateless or stateful (configurable replay cache).
- Subscribers: One-to-many.
- Use Case: One-time events like navigation, showing snackbars, or broadcasting updates where initial state doesn't matter.
Summary Table
| Feature | Flow | StateFlow | SharedFlow |
|---|---|---|---|
| Stream Type | Cold | Hot | Hot |
| Initial Value | No | Yes | Optional |
| Replay | No | Latest (1) | Configurable |
| Subscribers | 1:1 | 1:N | 1:N |
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚