Modern Android applications often contain multiple UI components interacting with shared application state.
Consider an e-commerce application where users can add products to a shopping cart, increase or decrease quantities, remove products, and complete purchases.
Every interaction changes the application’s state.
Without a consistent state management approach, these changes can become difficult to track.
For example:
- A button updates one part of the UI but not another.
- Cart totals become inconsistent.
- Multiple components modify the same state.
- Navigation happens more than once.
- Snackbar messages disappear unexpectedly.
- Business logic becomes mixed with composables.
- Unit testing becomes complicated.
Unidirectional Data Flow (UDF) helps solve these problems by defining a predictable direction for user actions and state updates.
In this tutorial, we’ll explore UDF using Kotlin, Jetpack Compose, ViewModel, StateFlow, and MVVM architecture.
We’ll also build a Shopping Cart application to demonstrate these concepts.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What Unidirectional Data Flow means
- Why UDF matters
- UI events and actions
- Immutable UI state
- StateFlow integration
- ViewModel event handling
- Reducer-style state updates
- Side effects
- Navigation handling
- Snackbar handling
- State hoisting
- UDF vs MVVM vs MVI
- Practical Shopping Cart implementation
- Testing UDF
- Common mistakes
- Production best practices
1. What Is Unidirectional Data Flow?
Unidirectional Data Flow is a state management approach where information follows a predictable direction.
The UI sends user actions to a state holder.
The state holder processes those actions and updates the state.
The UI observes the new state and renders it.
Basic UDF Architecture
User Interaction
|
v
Jetpack Compose
|
| UI Event
v
ViewModel
|
| Process Event
v
Update State
|
v
StateFlow
|
| New UI State
v
Jetpack Compose
Explanation
The ViewModel owns the screen state.
The UI does not directly modify that state.
Instead, the UI sends actions describing what the user wants to do.
Benefits
- Predictable state transitions
- Clear state ownership
- Easier debugging
- Better testability
- Reduced accidental coupling
- Consistent UI behavior
2. Why Is UDF Important in Jetpack Compose?
Jetpack Compose is a declarative UI toolkit.
Instead of manually modifying UI widgets, developers describe the UI based on state.
Traditional Imperative Approach
textView.text = "Cart: 3 items"
The application directly changes a UI component.
Declarative Compose Approach
@Composable
fun CartSummary(itemCount: Int) {
Text(
text = "Cart: $itemCount items"
)
}
When itemCount changes, Compose can update the displayed text.
Important Principle
The UI should be driven by state.
UI = Render(State)
UDF complements this model by defining how user actions produce new state.
3. Understanding the Three Core Parts of UDF
A typical UDF implementation contains three main concepts.
1. Events
Events describe user actions or other inputs.
Examples:
- AddProduct
- RemoveProduct
- IncreaseQuantity
- DecreaseQuantity
- Checkout
2. State
State represents what the screen currently displays.
Examples:
- Cart products
- Total amount
- Loading status
- Error message
3. State Holder
The state holder processes events and produces updated state.
In Android, ViewModel is commonly used as the screen-level state holder.
Architecture
Events
|
v
ViewModel
|
v
State
|
v
Compose UI
4. What Are UI Events?
UI events represent interactions that the application needs to handle.
Example
sealed interface CartAction {
data class AddProduct(
val productId: Int
) : CartAction
data class RemoveProduct(
val productId: Int
) : CartAction
data class IncreaseQuantity(
val productId: Int
) : CartAction
data class DecreaseQuantity(
val productId: Int
) : CartAction
data object Checkout : CartAction
}
Explanation
Each action represents an intention.
The UI sends an action to the ViewModel.
The ViewModel decides how the state should change.
Why Use a Sealed Interface?
A sealed interface defines a known set of action types.
A when expression can handle all supported actions explicitly.
Important
A sealed action type is useful for complex screens, but simple screens can use individual ViewModel functions.
UDF does not require every application to use a single event dispatcher.
5. Understanding Immutable UI State
Immutable UI state represents a snapshot of the screen.
Example
data class CartUiState(
val items: List<CartItem> = emptyList(),
val totalPrice: Double = 0.0,
val isCheckingOut: Boolean = false,
val errorMessage: String? = null
)
Explanation
The state object describes the current UI.
When data changes, the ViewModel creates a new state value.
Example State Update
_uiState.update { current ->
current.copy(
isCheckingOut = true
)
}
Benefits
- Predictable updates
- Easier testing
- Clear state ownership
- Reduced accidental mutation
Best Practice
Prefer immutable collections and data classes for UI state.
Avoid exposing mutable collections that other components can modify without producing a new state value.
6. StateFlow in UDF Architecture
StateFlow is commonly used to expose UI state from ViewModel.
Example
class CartViewModel : ViewModel() {
private val _uiState =
MutableStateFlow(CartUiState())
val uiState: StateFlow<CartUiState> =
_uiState.asStateFlow()
}
Explanation
The ViewModel owns MutableStateFlow.
The UI observes the read-only StateFlow.
This prevents the UI from directly modifying ViewModel state.
7. Handling Events in ViewModel
A ViewModel can expose a function that accepts actions.
Example
fun onAction(action: CartAction) {
when (action) {
is CartAction.AddProduct -> {
addProduct(action.productId)
}
is CartAction.RemoveProduct -> {
removeProduct(action.productId)
}
is CartAction.IncreaseQuantity -> {
increaseQuantity(action.productId)
}
is CartAction.DecreaseQuantity -> {
decreaseQuantity(action.productId)
}
CartAction.Checkout -> {
checkout()
}
}
}
Explanation
The ViewModel acts as the central event handler.
Each action is processed according to application rules.
Benefits
- Centralized event handling
- Predictable behavior
- Easier testing
- Clear separation of concerns
8. What Is a Reducer?
A reducer is a function that takes the current state and an action and produces a new state.
Conceptually:
New State = Reduce(Current State, Action)
Example
data class CounterState(
val count: Int = 0
)
sealed interface CounterAction {
data object Increment : CounterAction
data object Decrement : CounterAction
}
Reducer Function
fun reduce(
state: CounterState,
action: CounterAction
): CounterState {
return when (action) {
CounterAction.Increment -> {
state.copy(count = state.count + 1)
}
CounterAction.Decrement -> {
state.copy(count = state.count - 1)
}
}
}
Explanation
The reducer is a pure function.
It does not perform network requests, database operations, or navigation.
It calculates the next state from its inputs.
Benefits
- Deterministic behavior
- Easy unit testing
- Reusable transition logic
- Clear separation between state changes and side effects
9. What Are Side Effects?
A side effect is an operation that interacts with something outside a pure state calculation.
Examples include:
- Network requests
- Database writes
- Logging
- Navigation
- Showing a Snackbar
- Requesting permissions
Example
fun loadProducts() {
viewModelScope.launch {
val products = repository.getProducts()
_uiState.update {
it.copy(products = products)
}
}
}
The repository request is a side effect.
Updating state afterward makes the result observable to the UI.
Important
Not every side effect belongs inside ViewModel.
For example, UI-specific operations such as displaying a Snackbar should normally be performed by the UI layer in response to an appropriate state or event.
10. UDF vs MVVM vs MVI
These concepts are related but not identical.
| Concept | Primary Focus |
|---|---|
| MVVM | Separating View and ViewModel responsibilities |
| UDF | Predictable direction of actions and state |
| MVI | Intent-driven state transitions, often with reducers |
| Clean Architecture | Application boundaries and dependency direction |
Can They Work Together?
Yes.
A modern Android application can use:
- Clean Architecture for dependency boundaries
- MVVM for presentation organization
- UDF for state management
- Reducer-style functions for complex state transitions
Recommended Approach
Use the simplest combination that solves your application’s requirements.
Do not introduce unnecessary architectural abstractions into small screens.
Practical Mini-Project: Shopping Cart Using UDF
Now let’s build a Shopping Cart application using Jetpack Compose.
Features
- Display available products
- Add products to cart
- Increase quantity
- Decrease quantity
- Remove products
- Calculate cart total
- Display cart statistics
- Handle checkout confirmation
- Manage UI state with StateFlow
- Process actions using UDF
Technology Stack
- Kotlin
- Jetpack Compose
- Material 3
- ViewModel
- StateFlow
- Kotlin Coroutines
- MVVM
- UDF
This project uses in-memory state to keep the focus on UDF.
A production application would normally use a repository and persistent storage for cart data.
11. Recommended Project Structure
com.example.udfcart/
│
├── model/
│ ├── Product.kt
│ └── CartItem.kt
│
├── presentation/
│ ├── CartAction.kt
│ ├── CartUiState.kt
│ ├── CartViewModel.kt
│ └── CartScreen.kt
│
└── MainActivity.kt
12. Step 1 — Create the Product Model
File: model/Product.kt
package com.example.udfcart.model
data class Product(
val id: Int,
val name: String,
val priceInPaise: Long
)
Explanation
Each product contains a unique identifier, name, and price.
We store the price in paise using Long rather than Double.
This avoids common floating-point rounding problems when calculating currency totals.
13. Step 2 — Create the Cart Item Model
File: model/CartItem.kt
package com.example.udfcart.model
data class CartItem(
val product: Product,
val quantity: Int
)
Explanation
CartItem represents a product and its selected quantity.
14. Step 3 — Create the Cart Actions
File: presentation/CartAction.kt
package com.example.udfcart.presentation
sealed interface CartAction {
data class AddProduct(
val productId: Int
) : CartAction
data class RemoveProduct(
val productId: Int
) : CartAction
data class IncreaseQuantity(
val productId: Int
) : CartAction
data class DecreaseQuantity(
val productId: Int
) : CartAction
data object Checkout : CartAction
data object CheckoutMessageShown : CartAction
}
Explanation
All supported user actions are defined in one place.
The ViewModel processes these actions and updates UI state.
15. Step 4 — Create the UI State
File: presentation/CartUiState.kt
package com.example.udfcart.presentation
import com.example.udfcart.model.CartItem
import com.example.udfcart.model.Product
data class CartUiState(
val products: List<Product> = emptyList(),
val cartItems: List<CartItem> = emptyList(),
val totalPriceInPaise: Long = 0L,
val totalQuantity: Int = 0,
val checkoutMessage: String? = null
)
Explanation
CartUiState contains everything required to render the shopping cart screen.
The checkout message is represented as state so it can be acknowledged after display.
16. Step 5 — Create the Cart ViewModel
File: presentation/CartViewModel.kt
package com.example.udfcart.presentation
import androidx.lifecycle.ViewModel
import com.example.udfcart.model.CartItem
import com.example.udfcart.model.Product
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class CartViewModel : ViewModel() {
private val availableProducts = listOf(
Product(
id = 1,
name = "Android Phone",
priceInPaise = 1_999_900L
),
Product(
id = 2,
name = "Bluetooth Speaker",
priceInPaise = 249_900L
),
Product(
id = 3,
name = "Smart Watch",
priceInPaise = 499_900L
),
Product(
id = 4,
name = "Wireless Headphones",
priceInPaise = 299_900L
)
)
private val _uiState = MutableStateFlow(
CartUiState(products = availableProducts)
)
val uiState: StateFlow<CartUiState> =
_uiState.asStateFlow()
fun onAction(action: CartAction) {
when (action) {
is CartAction.AddProduct -> {
addProduct(action.productId)
}
is CartAction.RemoveProduct -> {
removeProduct(action.productId)
}
is CartAction.IncreaseQuantity -> {
addProduct(action.productId)
}
is CartAction.DecreaseQuantity -> {
decreaseQuantity(action.productId)
}
CartAction.Checkout -> {
checkout()
}
CartAction.CheckoutMessageShown -> {
_uiState.update {
it.copy(checkoutMessage = null)
}
}
}
}
private fun addProduct(productId: Int) {
val product = availableProducts
.firstOrNull { it.id == productId }
?: return
_uiState.update { state ->
val existingItem = state.cartItems
.firstOrNull {
it.product.id == productId
}
val updatedItems = if (existingItem == null) {
state.cartItems + CartItem(
product = product,
quantity = 1
)
} else {
state.cartItems.map { item ->
if (item.product.id == productId) {
item.copy(
quantity = item.quantity + 1
)
} else {
item
}
}
}
state.withUpdatedCart(updatedItems)
}
}
private fun removeProduct(productId: Int) {
_uiState.update { state ->
val updatedItems = state.cartItems.filterNot {
it.product.id == productId
}
state.withUpdatedCart(updatedItems)
}
}
private fun decreaseQuantity(productId: Int) {
_uiState.update { state ->
val updatedItems = state.cartItems.mapNotNull { item ->
if (item.product.id != productId) {
item
} else if (item.quantity > 1) {
item.copy(
quantity = item.quantity - 1
)
} else {
null
}
}
state.withUpdatedCart(updatedItems)
}
}
private fun checkout() {
_uiState.update { state ->
if (state.cartItems.isEmpty()) {
state.copy(
checkoutMessage = "Your cart is empty"
)
} else {
state.withUpdatedCart(
updatedItems = emptyList()
).copy(
checkoutMessage =
"Demo checkout completed successfully"
)
}
}
}
private fun CartUiState.withUpdatedCart(
updatedItems: List<CartItem>
): CartUiState {
return copy(
cartItems = updatedItems,
totalQuantity = updatedItems.sumOf {
it.quantity
},
totalPriceInPaise = updatedItems.sumOf {
it.product.priceInPaise * it.quantity
}
)
}
}
Explanation
The ViewModel receives actions and updates immutable state.
Every cart mutation recalculates:
- Cart items
- Total quantity
- Total price
This prevents different parts of the UI from maintaining conflicting totals.
Important
The checkout operation is a demonstration only.
It clears the local cart and displays a confirmation message.
It does not process payments or place a real order.
Production checkout should be handled through a secure backend with server-authoritative pricing and transaction validation.
17. Step 6 — Create the Shopping Cart Screen
File: presentation/CartScreen.kt
package com.example.udfcart.presentation
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.udfcart.model.CartItem
import com.example.udfcart.model.Product
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CartScreen(
viewModel: CartViewModel
) {
val uiState by viewModel.uiState
.collectAsStateWithLifecycle()
val snackbarHostState = remember {
SnackbarHostState()
}
LaunchedEffect(uiState.checkoutMessage) {
val message = uiState.checkoutMessage
if (message != null) {
snackbarHostState.showSnackbar(message)
viewModel.onAction(
CartAction.CheckoutMessageShown
)
}
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text("UDF Shopping Cart")
}
)
},
snackbarHost = {
SnackbarHost(snackbarHostState)
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp),
verticalArrangement =
Arrangement.spacedBy(12.dp)
) {
Text(
text = "Available Products",
style = MaterialTheme.typography.titleLarge
)
uiState.products.forEach { product ->
ProductRow(
product = product,
onAdd = {
viewModel.onAction(
CartAction.AddProduct(product.id)
)
}
)
}
HorizontalDivider()
Text(
text = "Your Cart",
style = MaterialTheme.typography.titleLarge
)
if (uiState.cartItems.isEmpty()) {
Text("Your cart is empty")
} else {
LazyColumn(
modifier = Modifier.weight(1f),
verticalArrangement =
Arrangement.spacedBy(8.dp)
) {
items(
items = uiState.cartItems,
key = { it.product.id }
) { item ->
CartItemRow(
item = item,
onIncrease = {
viewModel.onAction(
CartAction.IncreaseQuantity(
item.product.id
)
)
},
onDecrease = {
viewModel.onAction(
CartAction.DecreaseQuantity(
item.product.id
)
)
},
onRemove = {
viewModel.onAction(
CartAction.RemoveProduct(
item.product.id
)
)
}
)
}
}
}
Text(
text = "Items: ${uiState.totalQuantity}",
style = MaterialTheme.typography.titleMedium
)
Text(
text = "Total: ${formatPrice(uiState.totalPriceInPaise)}",
style = MaterialTheme.typography.titleLarge
)
Button(
onClick = {
viewModel.onAction(
CartAction.Checkout
)
},
modifier = Modifier.fillMaxWidth()
) {
Text("Checkout")
}
}
}
}
Explanation
CartScreen observes UI state using collectAsStateWithLifecycle().
It forwards user actions to the ViewModel.
The UI does not directly modify cart data.
18. Step 7 — Create the Product Row
Add this composable to CartScreen.kt.
@Composable
fun ProductRow(
product: Product,
onAdd: () -> Unit
) {
Card(
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalAlignment =
Alignment.CenterVertically
) {
Column(
modifier = Modifier.weight(1f)
) {
Text(
text = product.name,
style = MaterialTheme.typography.titleMedium
)
Text(
text = formatPrice(product.priceInPaise)
)
}
Button(
onClick = onAdd
) {
Text("Add")
}
}
}
}
Explanation
ProductRow displays product information.
It receives a callback rather than depending on ViewModel.
This makes it reusable and easier to test.
19. Step 8 — Create the Cart Item Row
Add this composable to CartScreen.kt.
@Composable
fun CartItemRow(
item: CartItem,
onIncrease: () -> Unit,
onDecrease: () -> Unit,
onRemove: () -> Unit
) {
Card(
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement =
Arrangement.spacedBy(8.dp)
) {
Text(
text = item.product.name,
style = MaterialTheme.typography.titleMedium
)
Text(
text = formatPrice(
item.product.priceInPaise * item.quantity
)
)
Row(
verticalAlignment =
Alignment.CenterVertically,
horizontalArrangement =
Arrangement.spacedBy(8.dp)
) {
OutlinedButton(
onClick = onDecrease
) {
Text("-")
}
Text(
text = item.quantity.toString()
)
OutlinedButton(
onClick = onIncrease
) {
Text("+")
}
TextButton(
onClick = onRemove
) {
Text("Remove")
}
}
}
}
}
Explanation
CartItemRow displays the quantity and subtotal for a product.
All user interactions are forwarded through callbacks.
20. Step 9 — Create a Price Formatting Function
Add this function to CartScreen.kt.
private fun formatPrice(
priceInPaise: Long
): String {
val rupees = priceInPaise / 100
val paise = priceInPaise % 100
return "₹$rupees.${paise.toString().padStart(2, '0')}"
}
Explanation
The function converts integer paise into a readable rupee amount.
For production applications, use locale-aware currency formatting.
21. Step 10 — Create MainActivity
File: MainActivity.kt
package com.example.udfcart
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.udfcart.presentation.CartScreen
import com.example.udfcart.presentation.CartViewModel
class MainActivity : ComponentActivity() {
override fun onCreate(
savedInstanceState: Bundle?
) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
val cartViewModel: CartViewModel =
viewModel()
CartScreen(
viewModel = cartViewModel
)
}
}
}
}
Explanation
MainActivity displays the Shopping Cart screen.
The ViewModel owns the cart state.
The Activity does not contain cart business logic.
22. Required Dependencies
Create an Android project with Jetpack Compose enabled.
Ensure the following dependencies are available.
dependencies {
implementation(
"androidx.activity:activity-compose:<version>"
)
implementation(
"androidx.lifecycle:lifecycle-viewmodel-ktx:<version>"
)
implementation(
"androidx.lifecycle:lifecycle-viewmodel-compose:<version>"
)
implementation(
"androidx.lifecycle:lifecycle-runtime-compose:<version>"
)
implementation(
"org.jetbrains.kotlinx:kotlinx-coroutines-android:<version>"
)
implementation(
"androidx.compose.material3:material3"
)
}
Replace placeholders with compatible stable versions.
Use the Compose BOM to manage Compose library versions when applicable.
23. Expected Application UI
Initial Screen
+--------------------------------+
| UDF Shopping Cart |
| |
| Available Products |
| |
| Android Phone [Add] |
| ₹19999.00 |
| |
| Bluetooth Speaker [Add] |
| ₹2499.00 |
| |
| Smart Watch [Add] |
| ₹4999.00 |
| |
| Wireless Headphones [Add] |
| ₹2999.00 |
| |
| Your Cart |
| |
| Your cart is empty |
| |
| Items: 0 |
| Total: ₹0.00 |
| |
| [Checkout] |
+--------------------------------+
After Adding Products
+--------------------------------+
| UDF Shopping Cart |
| |
| Available Products |
| ... |
| |
| Your Cart |
| |
| Android Phone |
| ₹19999.00 |
| [-] 1 [+] [Remove] |
| |
| Bluetooth Speaker |
| ₹4998.00 |
| [-] 2 [+] [Remove] |
| |
| Items: 3 |
| Total: ₹24997.00 |
| |
| [Checkout] |
+--------------------------------+
Explanation
The UI automatically updates when cart state changes.
The ViewModel recalculates totals after every cart mutation.
24. How the Complete UDF Application Works
Step 1: User Taps Add
The user taps Add for a product.
Step 2: UI Sends an Action
viewModel.onAction(
CartAction.AddProduct(product.id)
)
Step 3: ViewModel Processes the Action
The ViewModel finds the selected product.
Step 4: State Is Updated
The ViewModel creates a new cart state.
Step 5: StateFlow Emits the Latest State
The new CartUiState becomes available to collectors.
Step 6: Compose Observes the State
collectAsStateWithLifecycle() receives the updated state.
Step 7: UI Recomposition
Compose updates the cart list, quantity, and total price.
This demonstrates the complete UDF cycle.
25. Handling Navigation in UDF
Navigation is a UI responsibility.
A ViewModel should generally express that an operation has completed or that navigation is needed, without depending directly on NavController.
Example
data class LoginUiState(
val isLoggedIn: Boolean = false
)
Compose
LaunchedEffect(uiState.isLoggedIn) {
if (uiState.isLoggedIn) {
navController.navigate("home") {
popUpTo("login") {
inclusive = true
}
launchSingleTop = true
}
}
}
Explanation
The ViewModel exposes login state.
The UI reacts to that state and performs navigation.
Best Practice
Design navigation so repeated state observation does not create duplicate destinations.
Use appropriate back-stack handling and idempotent navigation behavior.
26. Handling Snackbar Messages
Snackbar display is a UI-specific operation.
A useful approach is to expose a pending message in UI state.
Example
data class ScreenUiState(
val message: String? = null
)
Compose
LaunchedEffect(uiState.message) {
val message = uiState.message
if (message != null) {
snackbarHostState.showSnackbar(message)
viewModel.onMessageShown()
}
}
Explanation
The ViewModel exposes a message.
The UI displays the Snackbar.
After handling, the UI acknowledges the message.
Important
For repeated identical messages or multiple queued messages, use unique identifiers or a queue-based state model.
A single nullable string cannot represent multiple identical pending messages reliably.
27. Reducer Pattern in Larger Applications
As state transitions become more complex, a dedicated reducer can improve organization.
Example
data class CounterUiState(
val count: Int = 0
)
sealed interface CounterAction {
data object Increment : CounterAction
data object Decrement : CounterAction
data object Reset : CounterAction
}
Reducer
fun counterReducer(
state: CounterUiState,
action: CounterAction
): CounterUiState {
return when (action) {
CounterAction.Increment -> {
state.copy(count = state.count + 1)
}
CounterAction.Decrement -> {
state.copy(count = state.count - 1)
}
CounterAction.Reset -> {
state.copy(count = 0)
}
}
}
ViewModel Integration
fun onAction(action: CounterAction) {
_uiState.update { current ->
counterReducer(current, action)
}
}
Benefits
- Pure state transitions
- Easier unit testing
- Predictable behavior
- Clearer event processing
28. Testing UDF State Transitions
One of the main benefits of UDF is predictable testing.
Example ViewModel Test
@Test
fun `adding product updates cart state`() {
val viewModel = CartViewModel()
viewModel.onAction(
CartAction.AddProduct(1)
)
val state = viewModel.uiState.value
assertEquals(
1,
state.totalQuantity
)
assertEquals(
1_999_900L,
state.totalPriceInPaise
)
}
Explanation
The test sends an action and verifies the resulting state.
No Android UI is required.
Important
Use the appropriate JUnit dependencies and test environment for your project.
29. Testing Reducers
Pure reducers are especially easy to test.
Example
@Test
fun `increment increases count`() {
val initialState = CounterUiState(
count = 5
)
val result = counterReducer(
initialState,
CounterAction.Increment
)
assertEquals(
6,
result.count
)
}
Explanation
The reducer receives inputs and returns a result.
It does not require coroutines, a database, or Android framework components.
30. Common UDF Architecture Mistakes
Mistake 1: Modifying State Directly from Composables
Keep screen-level mutable state owned by the appropriate state holder.
Mistake 2: Using Mutable Collections in UI State
Prefer immutable snapshots.
Mistake 3: Performing Business Logic in UI Components
Move reusable business logic into ViewModels, use cases, or domain components.
Mistake 4: Creating Too Many Event Types
Do not introduce unnecessary event abstractions for simple screens.
Mistake 5: Using SharedFlow Without Considering Lifecycle
Transient event delivery may be lost when the UI is inactive.
Mistake 6: Mixing Navigation Logic into Repositories
Keep navigation decisions and execution in appropriate presentation components.
Mistake 7: Ignoring Coroutine Cancellation
Preserve cancellation when handling asynchronous operations.
Mistake 8: Recalculating State in Multiple Places
Centralize important state transformations.
Mistake 9: Making ViewModels Too Large
Extract complex business rules into appropriate domain components.
Mistake 10: Skipping State Transition Tests
Test actions and their expected results.
31. Production Best Practices
Follow these recommendations:
- Keep UI state immutable.
- Expose read-only StateFlow.
- Define clear state ownership.
- Use Unidirectional Data Flow.
- Keep composables focused on rendering.
- Forward user actions through callbacks.
- Use ViewModel for screen-level state.
- Use repositories for data access.
- Use pure reducers when helpful.
- Keep side effects outside pure reducers.
- Handle coroutine cancellation correctly.
- Use lifecycle-aware Flow collection.
- Model important outcomes as state.
- Acknowledge handled messages and outcomes.
- Avoid unnecessary architectural complexity.
- Test state transitions independently.
- Use persistent storage for durable data.
- Profile performance before optimizing.
32. UDF Quick Reference
| Concept | Purpose |
|---|---|
| UDF | Predictable action and state flow |
| UI Action | Represents user intention |
| UI State | Current screen representation |
| ViewModel | Screen-level state holder |
| StateFlow | Observable state |
| MutableStateFlow | Mutable state holder |
| Reducer | Pure state transition function |
| Side Effect | External operation |
| State Hoisting | Moving state ownership upward |
| MVVM | Presentation architecture |
| MVI | Intent-driven state management approach |
| Repository | Data access abstraction |
| collectAsStateWithLifecycle() | Lifecycle-aware state collection |
| LaunchedEffect | Compose-managed coroutine side effect |
33. Practical Exercises
Exercise 1: Counter UDF
Build a counter using actions, state, and a reducer.
Exercise 2: Login Form
Create login state with email, password, loading, and error information.
Exercise 3: Product List
Implement AddProduct and RemoveProduct actions.
Exercise 4: Shopping Cart
Build the complete Shopping Cart application.
Exercise 5: Quantity Controls
Add increase and decrease quantity actions.
Exercise 6: Checkout State
Add loading and completion states for a simulated checkout.
Exercise 7: Snackbar
Display and acknowledge a confirmation message.
Exercise 8: Navigation
Navigate to a success screen after a completed operation.
Exercise 9: Reducer Testing
Write unit tests for pure state transitions.
Exercise 10: Repository Integration
Replace in-memory cart state with a repository backed by Room.
34. Frequently Asked Questions
What is Unidirectional Data Flow in Android?
UDF is an approach where user actions and state updates follow predictable paths.
Why use UDF with Jetpack Compose?
Compose renders UI from state, making UDF a natural approach for managing interactions and updates.
Is UDF the same as MVVM?
No.
MVVM organizes presentation responsibilities.
UDF defines the direction of actions and state updates.
They can be used together.
What is the difference between UDF and MVI?
UDF is a general data-flow principle.
MVI is a more specific architectural approach often built around intents, state, and reducer-style transitions.
What is a reducer?
A reducer is a function that calculates new state from current state and an action.
Should every Android application use reducers?
No.
Reducers are useful when state transitions become complex.
How should navigation be handled?
The UI should generally execute navigation in response to appropriate application state or presentation signals.
Can StateFlow be used with UDF?
Yes.
StateFlow is commonly used to expose observable UI state.
How do I test UDF?
Send actions to the state holder and verify the resulting state.
Pure reducers can be tested independently.
Is UDF suitable for production Android applications?
Yes.
UDF can improve predictability, maintainability, and testability when implemented appropriately.
What We’ve Learned
In this tutorial, we explored:
- Unidirectional Data Flow fundamentals
- UI actions and events
- Immutable UI state
- ViewModel event handling
- StateFlow integration
- Reducer-style state updates
- Side effects
- UDF vs MVVM vs MVI
- Jetpack Compose integration
- Practical Shopping Cart application
- Navigation handling
- Snackbar handling
- Reducer testing
- Common mistakes
- Production best practices
Unidirectional Data Flow is an important concept for building predictable Android applications.
By combining Kotlin, Jetpack Compose, ViewModel, StateFlow, and clear state ownership, developers can create interfaces that are easier to understand, test, and maintain.
The most important principle is simple:
User actions flow toward the state holder, and updated state flows back to the UI.
What’s Next?
In our next tutorial:
Article 43 — Dependency Injection in Android with Kotlin: Manual DI, Constructor Injection & Hilt Fundamentals
You’ll learn:
- What Dependency Injection is
- Why Dependency Injection matters
- Dependency Inversion Principle
- Constructor Injection
- Manual Dependency Injection
- Dependency Containers
- Interface-based dependencies
- Hilt fundamentals
- ViewModel injection
- Repository injection
- Testing with fake dependencies
- Practical Android mini-project
- Production best practices
Happy Coding!
Continue learning modern Android development with Moiks Developer Blog.