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
186: Unidirectional Data Flow Concepts
A few years ago, I was mentoring a developer who was building a complex shopping cart for an e-commerce app. He had a bug that would have driven anyone insane: occasionally, the "Total Price" would just reset to zero, even though the cart was full of items. After two days of debugging, we found the culprit. He had logic in the CartFragment that updated the price, logic in the CouponViewModel that updated the price, and a listener in the ShippingSelector that also touched the price. They were all fighting over the same variable, triggering a chain reaction of updates that eventually looped back and cleared the state.
This is exactly what happens when you have "bi-directional" or fragmented data flow. When anyone can change anything at any time, you lose the ability to reason about your app's state. To fix this, we use Unidirectional Data Flow (UDF). The core idea is simple: state moves down, and events move up.
The Single Source of Truth
In a UDF architecture, the UI doesn't "own" the data; it simply reflects it. I always tell my team to think of the UI as a pure function: UI = f(State). The ViewModel (or a similar state holder) maintains a single, immutable state object. The UI observes this state—usually via a StateFlow in Kotlin—and renders whatever it's told to render.
Because the state is immutable, the UI cannot simply reach into the state and change a value. If you want to change the price in the shopping cart, you can't just do state.total = 0. You have to create a new version of the state with the updated value. This prevents those erratic "ping-pong" updates where one change triggers another, which triggers the first one again.
data class CartState(
val items: List<CartItem> = emptyList(),
val totalPrice: Double = 0.0,
val isApplyingCoupon: Boolean = false
)
Routing Intentions via Events
If the UI can't change the state, how does anything actually happen? This is where "events" (sometimes called Intents or Actions) come in. Instead of the UI manipulating data, it emits an event describing what the user intended to do. It’s the difference between saying "Set the total to $50" and saying "The user clicked the Apply Coupon button."
The flow looks like this: the user clicks a button $\rightarrow$ the UI sends an event to the ViewModel $\rightarrow$ the ViewModel processes the logic $\rightarrow$ the ViewModel updates the state $\rightarrow$ the UI observes the new state and redraws. The data never flows "sideways" or "backwards." It's a strict loop.
sealed class CartEvent {
data class ItemAdded(val item: CartItem) : CartEvent()
data class CouponApplied(val code: String) : CartEvent()
object CartCleared : CartEvent()
}
class CartViewModel : ViewModel() {
private val _state = MutableStateFlow(CartState())
val state: StateFlow<CartState> = _state.asStateFlow()
fun onEvent(event: CartEvent) {
when (event) {
is CartEvent.ItemAdded $\rightarrow$ updateItems(event.item)
is CartEvent.CouponApplied $\rightarrow$ applyCoupon(event.code)
CartEvent.CartCleared $\rightarrow$ _state.value = CartState()
}
}
private fun updateItems(item: CartItem) {
val newList = _state.value.items + item
val newTotal = newList.sumOf { it.price }
_state.value = _state.value.copy(items = newList, totalPrice = newTotal)
}
}
I've found that this pattern drastically reduces the "it works on my machine but crashes randomly" type of bugs. When you're debugging, you no longer have to hunt through five different files to find who changed a variable. You just look at the onEvent function; that's the only place where state transitions are allowed to happen.
📋 Practical Task
Implementing a Synchronized Shopping Cart State Manager
You are tasked with fixing a "leaky" state implementation. Currently, the ProductPage is directly modifying a global CartManager object, causing race conditions. Your goal is to refactor this into a Unidirectional Data Flow pattern.
Requirements:
- Create a
CartStatedata class containing a list ofProductobjects and atotalQuantityinteger. - Create a
CartEventsealed class with two events:AddToCart(product: Product)andRemoveFromCart(productId: String). - Implement a
CartViewModelthat uses aMutableStateFlowto manage theCartState. - Implement a function
handleEvent(event: CartEvent)inside the ViewModel that handles both events by emitting a new copy of the state (using the.copy()method). - Ensure the
totalQuantityis automatically recalculated whenever an item is added or removed.
Constraints: The CartState must be exposed to the outside world as a read-only StateFlow to ensure the UI cannot modify the state directly.
There are no comments for now.