Skip to Content
Course content

36: StateFlow and SharedFlow

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 StateFlow that 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 SharedFlow that emits an error message (a String) whenever a payment fails. This should not be remembered if the screen is rotated.

Requirements:

  1. Implement a PaymentViewModel class.
  2. 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").
  3. Ensure the StateFlow and SharedFlow are exposed as read-only versions to the outside world.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.