Skip to Content
Course content

186: Unidirectional Data Flow Concepts

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

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 CartState data class containing a list of Product objects and a totalQuantity integer.
  • Create a CartEvent sealed class with two events: AddToCart(product: Product) and RemoveFromCart(productId: String).
  • Implement a CartViewModel that uses a MutableStateFlow to manage the CartState.
  • 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 totalQuantity is 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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.