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

I see this a lot when developers transition from LiveData or RxJava: they assume that the moment they define a flow { ... } block, the code inside that block starts running. They treat a Flow like a background task that's already been kicked off.

The "Immediate Execution" Myth

Let's look at a quick example to prove why that's wrong. Imagine you're building a simple sensor reader that emits a value every second. You might write something like this:

fun getSensorReadings() = flow {
    println("Sensor started!") // I'll bet you think this prints immediately
    emit(10)
    emit(20)
    emit(30)
}

// In your main function:
val readings = getSensorReadings() 
println("Flow object created.")

If you run this, you'll see "Flow object created" in your console, but you will not see "Sensor started!". This is the "aha!" moment. The flow didn't actually "do" anything; you just created a blueprint for a stream. Nothing happens until you call collect().

Cold Flows are just blueprints

The standard flow { ... } is what we call a Cold Flow. Think of it like a YouTube video. The video exists on the server, but it doesn't start playing until you click the "Play" button. More importantly, if two different people watch the same video, they both start from the beginning. They get their own independent stream of data.

If you call collect() on that sensor flow twice, the println("Sensor started!") will execute twice, and both collectors will receive 10, 20, and 30. This is great for things like database queries or network requests where you want a fresh set of data every time you start listening.

Hot Flows: The Live Broadcast

Now, imagine you need something different. Maybe you're tracking the current price of Bitcoin. You don't want every new observer to restart the price history from five years ago; you want them to see the current price right now, and then see updates as they happen in real-time.

This is a Hot Flow. Unlike Cold Flows, Hot Flows exist independently of their collectors. They are like a radio station. The music is playing whether you have your radio tuned in or not. If you tune in late, you've missed the first half of the song.

In Kotlin, the two primary Hot Flows are StateFlow and SharedFlow:

  • StateFlow: Always holds a single value (a state). It requires an initial value and always emits the current state to new collectors immediately. It's essentially a Flow-based version of LiveData.
  • SharedFlow: A more general-purpose broadcast channel. It doesn't necessarily hold a "current state"β€”it just pushes events to whoever is listening at that moment.
val priceUpdates = MutableStateFlow(0.0) // Hot! It exists immediately.

// Somewhere else in your code:
priceUpdates.value = 65000.0 // Updating the value without any collectors!

// Now a collector joins:
priceUpdates.collect { price -> 
    println("Current price is $price") // Immediately prints 65000.0
}

I've found that the hardest part for most engineers is deciding which one to use. My rule of thumb: if the data represents a state (like "is the user logged in?"), go with StateFlow. If the data represents an event (like "show a snackbar message"), go with SharedFlow. If it's a request (like "fetch users from API"), keep it as a Cold Flow.




πŸ“‹ Practical Task

Refactoring the UserSession Manager

You are working on a User Session manager. Currently, the userStatusFlow is implemented as a Cold Flow, which means every time a UI component collects it, it re-triggers the database check to see if the user is logged in. This is causing unnecessary database load.

Your Task: Convert the userStatusFlow from a Cold Flow to a StateFlow so that the login status is cached and shared across all collectors without re-running the database logic.

class UserSessionManager(private val db: UserDatabase) {
    // CURRENT IMPLEMENTATION (Cold Flow - WRONG)
    fun userStatusFlow() = flow {
        println("Checking DB... (Expensive Operation)")
        emit(db.isUserLoggedIn())
    }
}

Requirements:

  • Use MutableStateFlow to hold the current status.
  • Initialize the StateFlow by calling db.isUserLoggedIn() once.
  • Expose the flow as a read-only StateFlow to prevent external classes from modifying the session state.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.