Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
36: StateFlow and SharedFlow
I've spent a lot of time fighting with "state" in UI development. You know the drill: you update a variable, but the screen doesn't reflect it, or worse, you rotate your phone and the app suddenly forgets everything the user just typed. We've looked at basic Flows, but they are "cold"—they don't hold onto data. They just produce it when someone starts listening. For a real app, we need something "hot."
The problem with cold flows in UI
Let's say we're building a simple User Profile screen. I want to track whether the user is currently "Online" or "Offline." My first instinct might be to use a simple flow:
val userStatus = flow {
while(true) {
val status = api.fetchStatus()
emit(status)
delay(5000)
}
}
Here is the catch: every time a new fragment or activity starts collecting this flow, the block inside flow { ... } restarts. If I have three different UI components listening to the status, I'm making three separate API calls every five seconds. That's a waste of bandwidth and battery. Plus, if a new collector joins, they have to wait up to five seconds before they get their first update. That "blank" state during the wait is a terrible user experience.
Adding a memory with StateFlow
I need a way to share a single source of truth that remembers the last value it emitted. This is where StateFlow comes in. I'll wrap my logic in a MutableStateFlow:
class UserViewModel {
private val _status = MutableStateFlow("Unknown")
val status: StateFlow<String> = _status
fun updateStatus(newStatus: String) {
_status.value = newStatus
}
}
Now, let's observe the difference. When I call status.collect { ... }, the collector immediately receives "Unknown" (the initial value). It doesn't have to wait for the next API update. If the status changes to "Online," everyone listening gets that update instantly. If a new screen opens and starts collecting, it immediately gets "Online."
It's essentially a variable that you can observe. It's perfect for state—things that describe "what the screen looks like right now."
When remembering is actually a bug
Now, let's try to use StateFlow for something else: a "Profile Updated" snackbar notification. I'll create a state for the message:
private val _message = MutableStateFlow<String?> (null)
val message: StateFlow<String?> = _message
fun onSaveClicked() {
// ... save logic ...
_message.value = "Profile saved successfully!"
}
This looks fine until I test it. I click save, the snackbar pops up. Great. Then, I rotate the screen. Because StateFlow remembers the last value, the new activity collects the flow, sees "Profile saved successfully!", and shows the snackbar again. But the user didn't save the profile again; they just rotated their phone. This is the classic "Event vs State" problem.
Broadcasting events with SharedFlow
I don't want the app to remember that a notification happened; I just want to broadcast the event and then forget about it. This is why we have SharedFlow. Let's swap it out:
private val _events = MutableSharedFlow<String>()
val events: SharedFlow<String> = _events
fun onSaveClicked() {
viewModelScope.launch {
_events.emit("Profile saved successfully!")
}
}
I noticed two big changes here. First, MutableSharedFlow doesn't require an initial value. Second, I have to use emit() inside a coroutine because SharedFlow is designed to handle backpressure (it doesn't just overwrite a .value property).
Now, when I rotate the screen and re-collect, nothing happens. The event was fired, the listener who was active at the time handled it, and it's gone. If no one is listening when emit() is called, the event is simply dropped. This is exactly what we want for one-time triggers like navigation, toasts, or alerts.
To recap my mental model: use StateFlow when you need to know "What is the current value?" and SharedFlow when you need to know "What just happened?"
📋 Practical Task
Build a Payment Processing Event System
You are building a payment screen. You need to manage two different types of data streams using the concepts from this lesson.
- The Payment State: Create a
StateFlowthat tracks the current status of the payment. The possible states are"Idle","Processing", and"Completed". It should start as"Idle". - The Error Event: Create a
SharedFlowthat emits an error message (a String) whenever a payment fails. This should not be remembered if the screen is rotated.
Requirements:
- Implement a
PaymentViewModelclass. - Create a function
processPayment()that:- Sets the state to
"Processing". - Simulates a network call (use
delay). - Randomly either sets the state to
"Completed"OR emits an error message like"Insufficient Funds"via the SharedFlow (and resets state to"Idle").
- Sets the state to
- Ensure the
StateFlowandSharedFloware exposed as read-only versions to the outside world.
There are no comments for now.