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
182: Cold vs Hot Flows
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
MutableStateFlowto hold the current status. - Initialize the
StateFlowby callingdb.isUserLoggedIn()once. - Expose the flow as a read-only
StateFlowto prevent external classes from modifying the session state.
There are no comments for now.