{"id":184,"date":"2026-10-20T03:54:00","date_gmt":"2026-10-20T03:54:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=184"},"modified":"2026-11-06T08:48:27","modified_gmt":"2026-11-06T08:48:27","slug":"android-viewmodel-ui-state-management-with-stateflow-and-jetpack-compose-complete-guide","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/android-viewmodel-ui-state-management-with-stateflow-and-jetpack-compose-complete-guide\/","title":{"rendered":"Android ViewModel &#038; UI State Management with StateFlow and Jetpack Compose: Complete Guide"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Managing UI state is one of the most important responsibilities in modern Android development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A simple Android application may contain only a few buttons and text fields. However, production applications often manage much more complex behavior.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Loading data from APIs<\/li>\n\n\n\n<li>Displaying database records<\/li>\n\n\n\n<li>Handling user input<\/li>\n\n\n\n<li>Managing search and filters<\/li>\n\n\n\n<li>Displaying errors<\/li>\n\n\n\n<li>Updating lists<\/li>\n\n\n\n<li>Preserving state during configuration changes<\/li>\n\n\n\n<li>Restoring important information after process recreation<\/li>\n\n\n\n<li>Handling asynchronous operations<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Without proper state management, applications can become difficult to maintain and debug.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Modern Android development provides powerful tools for solving these problems.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>ViewModel, Kotlin StateFlow, SavedStateHandle, and Jetpack Compose<\/strong> work together to create predictable and lifecycle-aware UI state management.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll explore these technologies and build a practical Task Manager application using MVVM architecture.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What You&#8217;ll Learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this tutorial, you&#8217;ll understand:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What UI state means in Android<\/li>\n\n\n\n<li>What Android ViewModel is<\/li>\n\n\n\n<li>ViewModel lifecycle<\/li>\n\n\n\n<li>StateFlow and MutableStateFlow<\/li>\n\n\n\n<li>StateFlow vs LiveData<\/li>\n\n\n\n<li>StateFlow vs SharedFlow<\/li>\n\n\n\n<li>Immutable UI state<\/li>\n\n\n\n<li>State hoisting<\/li>\n\n\n\n<li>Unidirectional Data Flow<\/li>\n\n\n\n<li>Lifecycle-aware Flow collection<\/li>\n\n\n\n<li>SavedStateHandle<\/li>\n\n\n\n<li>Configuration changes and process death<\/li>\n\n\n\n<li>Loading, success, and error states<\/li>\n\n\n\n<li>One-time UI events<\/li>\n\n\n\n<li>StateFlow with repositories<\/li>\n\n\n\n<li>ViewModel unit testing<\/li>\n\n\n\n<li>Production best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s begin!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. What Is UI State in Android?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">UI state represents the information required to render a screen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, consider a shopping application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Its UI state might contain:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Product list<\/li>\n\n\n\n<li>Loading status<\/li>\n\n\n\n<li>Selected category<\/li>\n\n\n\n<li>Search query<\/li>\n\n\n\n<li>Error message<\/li>\n\n\n\n<li>Refresh status<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>data class ProductUiState(\n    val products: List&lt;Product&gt; = emptyList(),\n    val isLoading: Boolean = false,\n    val searchQuery: String = \"\",\n    val errorMessage: String? = null\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI state describes what the screen should display.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the state changes, Jetpack Compose can automatically update the relevant UI.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Principle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI should be a function of its state.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>UI = Render(State)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of manually updating individual UI elements, developers update the state and let Compose render the result.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. What Is Android ViewModel?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel is an Android Jetpack component designed to manage UI-related state and presentation logic.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is commonly used with Activities, Fragments, and Jetpack Compose.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Main Responsibilities<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Hold screen-level UI state<\/li>\n\n\n\n<li>Coordinate repository operations<\/li>\n\n\n\n<li>Handle user actions<\/li>\n\n\n\n<li>Execute coroutines<\/li>\n\n\n\n<li>Transform application data into presentation state<\/li>\n\n\n\n<li>Survive configuration changes while its owner remains active<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class CounterViewModel : ViewModel() {\n\n    private val _count = MutableStateFlow(0)\n\n    val count: StateFlow&lt;Int&gt; =\n        _count.asStateFlow()\n\n    fun increment() {\n        _count.update { it + 1 }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel owns the mutable state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes a read-only StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When increment() is called, the state changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack Compose can then recompose the relevant UI.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Understanding the ViewModel Lifecycle<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel instances are retained across configuration changes while their ViewModelStoreOwner remains active.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Activity Created\n       |\n       v\nViewModel Created\n       |\n       v\nDevice Rotation\n       |\n       v\nActivity Recreated\n       |\n       v\nExisting ViewModel Reused\n       |\n       v\nOwner Permanently Destroyed\n       |\n       v\nViewModel Cleared<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Is This Important?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Without an appropriate state holder, an Activity recreation may cause unnecessary data loading or loss of temporary screen state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel helps manage screen-level state across configuration changes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel does not automatically preserve all in-memory state after process death.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For state that must be restored after process recreation, use SavedStateHandle or persistent storage, depending on the data.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. What Is StateFlow?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow is a hot Flow from Kotlin Coroutines that holds a current value and emits updates to collectors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is especially useful for observable UI state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>private val _username =\n    MutableStateFlow(\"Android Developer\")\n\nval username: StateFlow&lt;String&gt; =\n    _username.asStateFlow()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Key Characteristics<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Always has a current value<\/li>\n\n\n\n<li>Exposes the latest state through value<\/li>\n\n\n\n<li>Supports multiple collectors<\/li>\n\n\n\n<li>Emits updates when the state changes<\/li>\n\n\n\n<li>Uses equality-based conflation<\/li>\n\n\n\n<li>Integrates naturally with Kotlin Coroutines<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow is not lifecycle-aware by itself.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Lifecycle awareness is provided by how it is collected in Android components.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. MutableStateFlow vs StateFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">MutableStateFlow allows state updates.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow provides read-only observation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Pattern<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProfileViewModel : ViewModel() {\n\n    private val _name =\n        MutableStateFlow(\"Guest\")\n\n    val name: StateFlow&lt;String&gt; =\n        _name.asStateFlow()\n\n    fun updateName(newName: String) {\n        _name.value = newName\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Keep MutableStateFlow Private?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exposing mutable state publicly allows other components to modify it directly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes state ownership less predictable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep mutable state private and expose read-only state.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. StateFlow vs LiveData<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both StateFlow and LiveData can represent observable state.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>StateFlow<\/th><th>LiveData<\/th><\/tr><tr><td>Kotlin Coroutines integration<\/td><td>Native<\/td><td>Requires adapters for some operations<\/td><\/tr><tr><td>Current value<\/td><td>Required<\/td><td>May initially be absent<\/td><\/tr><tr><td>Lifecycle awareness<\/td><td>Collector-dependent<\/td><td>Built into observation<\/td><\/tr><tr><td>Flow operators<\/td><td>Supported<\/td><td>Not directly<\/td><\/tr><tr><td>Jetpack Compose integration<\/td><td>Supported<\/td><td>Supported<\/td><\/tr><tr><td>Multiplatform-friendly API<\/td><td>Yes<\/td><td>Android-specific<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Which Should You Use?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For new Kotlin and Jetpack Compose applications, StateFlow is often a practical choice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">LiveData remains useful in existing applications and XML-based architectures.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. StateFlow vs SharedFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow and SharedFlow serve related but different purposes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">StateFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Best suited for observable state that has a current value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Current search query<\/li>\n\n\n\n<li>Product list<\/li>\n\n\n\n<li>Loading status<\/li>\n\n\n\n<li>Selected tab<\/li>\n\n\n\n<li>Screen UI state<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">SharedFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Useful for broadcasting values or events to collectors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Application-level event streams<\/li>\n\n\n\n<li>Notifications to active subscribers<\/li>\n\n\n\n<li>Non-state broadcasts<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>StateFlow<\/th><th>SharedFlow<\/th><\/tr><tr><td>Current value<\/td><td>Yes<\/td><td>Not required<\/td><\/tr><tr><td>Initial value<\/td><td>Required<\/td><td>Not required<\/td><\/tr><tr><td>Replay<\/td><td>Latest state<\/td><td>Configurable<\/td><\/tr><tr><td>Primary use<\/td><td>State<\/td><td>Broadcast streams<\/td><\/tr><tr><td>Equality conflation<\/td><td>Yes<\/td><td>Not automatically<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow does not guarantee delivery to a UI collector that is inactive or absent unless its configuration and consumption model explicitly account for that.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For important user-visible outcomes, model durable information as UI state.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Understanding Immutable UI State<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A screen can expose one immutable UI state object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>data class DashboardUiState(\n    val username: String = \"\",\n    val balance: Double = 0.0,\n    val isLoading: Boolean = false,\n    val errorMessage: String? = null\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">ViewModel<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class DashboardViewModel : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow(DashboardUiState())\n\n    val uiState: StateFlow&lt;DashboardUiState&gt; =\n        _uiState.asStateFlow()\n\n    fun updateUsername(name: String) {\n\n        _uiState.update { currentState -&gt;\n\n            currentState.copy(\n                username = name\n            )\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The data class represents a snapshot of screen state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The copy() function creates an updated state value.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Predictable state changes<\/li>\n\n\n\n<li>Easier testing<\/li>\n\n\n\n<li>Clear state ownership<\/li>\n\n\n\n<li>Simpler debugging<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. What Is Unidirectional Data Flow?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Unidirectional Data Flow, or UDF, means user actions and state updates follow a predictable direction.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"> <code>       User Interaction\n               |\n               v\n        Jetpack Compose\n               |\n               | Action\n               v\n           ViewModel\n               |\n               | Update\n               v\n            StateFlow\n               |\n               | State\n               v\n        Jetpack Compose<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun onSearchQueryChanged(query: String) {\n\n    _uiState.update {\n        it.copy(searchQuery = query)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI sends a search action.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel updates state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes the new state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Predictable behavior<\/li>\n\n\n\n<li>Easier debugging<\/li>\n\n\n\n<li>Clear ownership<\/li>\n\n\n\n<li>Better testability<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. State Hoisting in Jetpack Compose<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">State hoisting moves state ownership to a suitable parent component.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun SearchTextField(\n    query: String,\n    onQueryChange: (String) -&gt; Unit\n) {\n\n    OutlinedTextField(\n        value = query,\n        onValueChange = onQueryChange,\n        label = {\n            Text(\"Search\")\n        }\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SearchTextField receives its state and callback.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not own the search query.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Reusable composables<\/li>\n\n\n\n<li>Easier previews<\/li>\n\n\n\n<li>Better testing<\/li>\n\n\n\n<li>Clear state ownership<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Hoist state to the lowest appropriate common owner.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Not every temporary UI value needs to live in ViewModel.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Lifecycle-Aware StateFlow Collection<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In Jetpack Compose, StateFlow should usually be collected with lifecycle awareness.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Approach<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun DashboardScreen(\n    viewModel: DashboardViewModel\n) {\n\n    val uiState by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    Text(\n        text = uiState.username\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">collectAsStateWithLifecycle() collects the Flow according to the Android lifecycle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the lifecycle falls below the configured active state, collection is stopped and can restart later.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Dependency<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>implementation(\n    \"androidx.lifecycle:lifecycle-runtime-compose:&lt;version&gt;\"\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use a compatible stable version.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. Understanding SavedStateHandle<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SavedStateHandle provides access to state that can be saved and restored through Android&#8217;s saved-state mechanism.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is useful for small, important values such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Search queries<\/li>\n\n\n\n<li>Selected filters<\/li>\n\n\n\n<li>Navigation arguments<\/li>\n\n\n\n<li>Draft identifiers<\/li>\n\n\n\n<li>Selected item IDs<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class SearchViewModel(\n    private val savedStateHandle: SavedStateHandle\n) : ViewModel() {\n\n    val searchQuery: StateFlow&lt;String&gt; =\n        savedStateHandle.getStateFlow(\n            \"search_query\",\n            \"\"\n        )\n\n    fun updateSearchQuery(query: String) {\n\n        savedStateHandle&#91;\"search_query\"] = query\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The search query is stored in SavedStateHandle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It can be restored when Android recreates the component with previously saved state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SavedStateHandle is intended for small, Bundle-compatible state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not use it to store large datasets, images, or complete database records.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Saved-state restoration is also subject to Android&#8217;s normal saved-state lifecycle and is not a replacement for durable persistence.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Configuration Changes vs Process Death<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These two situations are different.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Configuration Change<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Examples:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Device rotation<\/li>\n\n\n\n<li>Certain display configuration changes<\/li>\n\n\n\n<li>Language or theme-related recreation<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel normally survives Activity recreation when its owner is retained.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Process Death<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Android may terminate the application process while it is in the background.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Ordinary ViewModel memory is lost.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SavedStateHandle can restore supported saved state when Android recreates the component with that state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Persistent storage is needed for durable application data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Storage<\/th><th>Configuration Change<\/th><th>Process Death<\/th><th>Durable App Restart<\/th><\/tr><tr><td>remember<\/td><td>Usually lost on recreation<\/td><td>No<\/td><td>No<\/td><\/tr><tr><td>rememberSaveable<\/td><td>Usually restored<\/td><td>Conditional saved-state restoration<\/td><td>No guarantee<\/td><\/tr><tr><td>ViewModel<\/td><td>Retained while owner survives<\/td><td>No<\/td><td>No<\/td><\/tr><tr><td>SavedStateHandle<\/td><td>Supported<\/td><td>Conditional saved-state restoration<\/td><td>No guarantee<\/td><\/tr><tr><td>Room \/ DataStore<\/td><td>Yes<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use ViewModel for screen state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use SavedStateHandle for small restorable state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use Room or DataStore for persistent information.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">Practical Mini-Project: Task Manager Using ViewModel and StateFlow<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s build a Task Manager application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Add tasks<\/li>\n\n\n\n<li>Mark tasks as completed<\/li>\n\n\n\n<li>Delete tasks<\/li>\n\n\n\n<li>Search tasks<\/li>\n\n\n\n<li>Filter All, Active, and Completed tasks<\/li>\n\n\n\n<li>Display task statistics<\/li>\n\n\n\n<li>Restore the search query using SavedStateHandle<\/li>\n\n\n\n<li>Manage state with StateFlow<\/li>\n\n\n\n<li>Use MVVM and Jetpack Compose<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Technology Stack<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Kotlin<\/li>\n\n\n\n<li>Jetpack Compose<\/li>\n\n\n\n<li>Material 3<\/li>\n\n\n\n<li>ViewModel<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>Kotlin Coroutines<\/li>\n\n\n\n<li>SavedStateHandle<\/li>\n\n\n\n<li>MVVM<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This project uses an in-memory repository to focus on state management.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Tasks will not persist after the application process is terminated.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll cover durable storage with Room in a future tutorial.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Recommended Project Structure<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>com.example.taskmanager\/\n\u2502\n\u251c\u2500\u2500 data\/\n\u2502   \u251c\u2500\u2500 TaskRepository.kt\n\u2502   \u2514\u2500\u2500 InMemoryTaskRepository.kt\n\u2502\n\u251c\u2500\u2500 model\/\n\u2502   \u2514\u2500\u2500 Task.kt\n\u2502\n\u251c\u2500\u2500 presentation\/\n\u2502   \u251c\u2500\u2500 TaskFilter.kt\n\u2502   \u251c\u2500\u2500 TaskUiState.kt\n\u2502   \u251c\u2500\u2500 TaskViewModel.kt\n\u2502   \u2514\u2500\u2500 TaskScreen.kt\n\u2502\n\u2514\u2500\u2500 MainActivity.kt<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. Step 1 \u2014 Create the Task Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>model\/Task.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.model\n\ndata class Task(\n    val id: Long,\n    val title: String,\n    val isCompleted: Boolean = false\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each task contains:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A unique identifier<\/li>\n\n\n\n<li>A title<\/li>\n\n\n\n<li>A completion status<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Step 2 \u2014 Create the Task Repository<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/TaskRepository.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.data\n\nimport com.example.taskmanager.model.Task\nimport kotlinx.coroutines.flow.StateFlow\n\ninterface TaskRepository {\n\n    val tasks: StateFlow&lt;List&lt;Task&gt;&gt;\n\n    suspend fun addTask(title: String)\n\n    suspend fun toggleTask(id: Long)\n\n    suspend fun deleteTask(id: Long)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository exposes observable tasks and operations to modify them.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Step 3 \u2014 Implement the In-Memory Repository<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/InMemoryTaskRepository.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.data\n\nimport com.example.taskmanager.model.Task\n\nimport kotlinx.coroutines.flow.MutableStateFlow\nimport kotlinx.coroutines.flow.StateFlow\nimport kotlinx.coroutines.flow.asStateFlow\nimport kotlinx.coroutines.flow.update\n\nclass InMemoryTaskRepository : TaskRepository {\n\n    private val _tasks =\n        MutableStateFlow&lt;List&lt;Task&gt;&gt;(emptyList())\n\n    override val tasks: StateFlow&lt;List&lt;Task&gt;&gt; =\n        _tasks.asStateFlow()\n\n    private var nextId = 1L\n\n    override suspend fun addTask(title: String) {\n\n        val trimmedTitle = title.trim()\n\n        if (trimmedTitle.isBlank()) {\n            return\n        }\n\n        val newTask = Task(\n            id = nextId++,\n            title = trimmedTitle\n        )\n\n        _tasks.update { current -&gt;\n            current + newTask\n        }\n    }\n\n    override suspend fun toggleTask(id: Long) {\n\n        _tasks.update { current -&gt;\n\n            current.map { task -&gt;\n\n                if (task.id == id) {\n\n                    task.copy(\n                        isCompleted = !task.isCompleted\n                    )\n\n                } else {\n\n                    task\n                }\n            }\n        }\n    }\n\n    override suspend fun deleteTask(id: Long) {\n\n        _tasks.update { current -&gt;\n\n            current.filterNot { task -&gt;\n                task.id == id\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository manages an in-memory task list.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow emits updates whenever tasks are added, modified, or deleted.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This implementation assumes task mutations are coordinated through a single logical owner.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For concurrent production writes, use a database with appropriate transactional guarantees.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. Step 4 \u2014 Create Task Filters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/TaskFilter.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.presentation\n\nenum class TaskFilter {\n\n    ALL,\n\n    ACTIVE,\n\n    COMPLETED\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The filter determines which tasks should be displayed.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Step 5 \u2014 Create the UI State<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/TaskUiState.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.presentation\n\nimport com.example.taskmanager.model.Task\n\ndata class TaskUiState(\n\n    val tasks: List&lt;Task&gt; = emptyList(),\n\n    val searchQuery: String = \"\",\n\n    val selectedFilter: TaskFilter = TaskFilter.ALL,\n\n    val totalTasks: Int = 0,\n\n    val completedTasks: Int = 0,\n\n    val activeTasks: Int = 0\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">TaskUiState contains everything the screen needs to render its content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI receives one consistent state object.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Step 6 \u2014 Create the Task ViewModel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/TaskViewModel.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.presentation\n\nimport androidx.lifecycle.SavedStateHandle\nimport androidx.lifecycle.ViewModel\nimport androidx.lifecycle.viewModelScope\n\nimport com.example.taskmanager.data.TaskRepository\n\nimport kotlinx.coroutines.flow.SharingStarted\nimport kotlinx.coroutines.flow.StateFlow\nimport kotlinx.coroutines.flow.combine\nimport kotlinx.coroutines.flow.stateIn\nimport kotlinx.coroutines.launch\n\nclass TaskViewModel(\n    private val repository: TaskRepository,\n    private val savedStateHandle: SavedStateHandle\n) : ViewModel() {\n\n    private val searchQuery =\n        savedStateHandle.getStateFlow(\n            \"search_query\",\n            \"\"\n        )\n\n    private val selectedFilter =\n        savedStateHandle.getStateFlow(\n            \"selected_filter\",\n            TaskFilter.ALL.name\n        )\n\n    val uiState: StateFlow&lt;TaskUiState&gt; = combine(\n        repository.tasks,\n        searchQuery,\n        selectedFilter\n    ) { tasks, query, filterName -&gt;\n\n        val filter = TaskFilter.entries\n            .firstOrNull { it.name == filterName }\n            ?: TaskFilter.ALL\n\n        val filteredTasks = tasks.filter { task -&gt;\n\n            val matchesSearch =\n                task.title.contains(\n                    query,\n                    ignoreCase = true\n                )\n\n            val matchesFilter = when (filter) {\n\n                TaskFilter.ALL -&gt; true\n\n                TaskFilter.ACTIVE -&gt; !task.isCompleted\n\n                TaskFilter.COMPLETED -&gt; task.isCompleted\n            }\n\n            matchesSearch &amp;&amp; matchesFilter\n        }\n\n        TaskUiState(\n            tasks = filteredTasks,\n            searchQuery = query,\n            selectedFilter = filter,\n            totalTasks = tasks.size,\n            completedTasks = tasks.count { it.isCompleted },\n            activeTasks = tasks.count { !it.isCompleted }\n        )\n\n    }.stateIn(\n        scope = viewModelScope,\n        started = SharingStarted.WhileSubscribed(5_000),\n        initialValue = TaskUiState(\n            searchQuery = searchQuery.value,\n            selectedFilter = TaskFilter.entries\n                .firstOrNull {\n                    it.name == selectedFilter.value\n                } ?: TaskFilter.ALL\n        )\n    )\n\n    fun updateSearchQuery(query: String) {\n\n        savedStateHandle&#91;\"search_query\"] = query\n    }\n\n    fun updateFilter(filter: TaskFilter) {\n\n        savedStateHandle&#91;\"selected_filter\"] = filter.name\n    }\n\n    fun addTask(title: String) {\n\n        viewModelScope.launch {\n            repository.addTask(title)\n        }\n    }\n\n    fun toggleTask(id: Long) {\n\n        viewModelScope.launch {\n            repository.toggleTask(id)\n        }\n    }\n\n    fun deleteTask(id: Long) {\n\n        viewModelScope.launch {\n            repository.deleteTask(id)\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel combines three state streams:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Repository tasks<\/li>\n\n\n\n<li>Search query<\/li>\n\n\n\n<li>Selected filter<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The combine() operator recalculates the UI state whenever any input changes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use stateIn()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">stateIn() converts the combined Flow into a StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel exposes one observable screen state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use WhileSubscribed(5_000)?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It keeps the upstream collection active briefly after the final subscriber disappears.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This can reduce unnecessary restarts during short lifecycle transitions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Store Filters in SavedStateHandle?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Search and filter selections are small pieces of state that may be useful to restore after process recreation.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Step 7 \u2014 Create the ViewModel Factory<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/TaskViewModelFactory.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.presentation\n\nimport androidx.lifecycle.SavedStateHandle\nimport androidx.lifecycle.ViewModel\nimport androidx.lifecycle.ViewModelProvider\nimport androidx.lifecycle.createSavedStateHandle\nimport androidx.lifecycle.viewmodel.CreationExtras\n\nimport com.example.taskmanager.data.TaskRepository\n\nclass TaskViewModelFactory(\n    private val repository: TaskRepository\n) : ViewModelProvider.Factory {\n\n    override fun &lt;T : ViewModel&gt; create(\n        modelClass: Class&lt;T&gt;,\n        extras: CreationExtras\n    ): T {\n\n        if (\n            modelClass.isAssignableFrom(\n                TaskViewModel::class.java\n            )\n        ) {\n\n            val savedStateHandle: SavedStateHandle =\n                extras.createSavedStateHandle()\n\n            @Suppress(\"UNCHECKED_CAST\")\n            return TaskViewModel(\n                repository = repository,\n                savedStateHandle = savedStateHandle\n            ) as T\n        }\n\n        throw IllegalArgumentException(\n            \"Unknown ViewModel class\"\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The factory provides the repository and a SavedStateHandle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The SavedStateHandle is created from ViewModel creation extras.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Step 8 \u2014 Create the Task Screen<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/TaskScreen.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager.presentation\n\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.lazy.LazyColumn\nimport androidx.compose.foundation.lazy.items\nimport androidx.compose.material3.*\nimport androidx.compose.runtime.*\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.unit.dp\n\nimport androidx.lifecycle.compose.collectAsStateWithLifecycle\n\nimport com.example.taskmanager.model.Task\n\n@OptIn(ExperimentalMaterial3Api::class)\n@Composable\nfun TaskScreen(\n    viewModel: TaskViewModel\n) {\n\n    val uiState by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    var newTaskTitle by rememberSaveable {\n        mutableStateOf(\"\")\n    }\n\n    Scaffold(\n        topBar = {\n\n            TopAppBar(\n                title = {\n                    Text(\"Task Manager\")\n                }\n            )\n        }\n    ) { paddingValues -&gt;\n\n        Column(\n            modifier = Modifier\n                .fillMaxSize()\n                .padding(paddingValues)\n                .padding(16.dp),\n            verticalArrangement =\n                Arrangement.spacedBy(16.dp)\n        ) {\n\n            Text(\n                text = \"Total: ${uiState.totalTasks} | \" +\n                    \"Active: ${uiState.activeTasks} | \" +\n                    \"Done: ${uiState.completedTasks}\",\n                style = MaterialTheme.typography.bodyMedium\n            )\n\n            Row(\n                horizontalArrangement =\n                    Arrangement.spacedBy(8.dp),\n                verticalAlignment =\n                    Alignment.CenterVertically\n            ) {\n\n                OutlinedTextField(\n                    value = newTaskTitle,\n                    onValueChange = {\n                        newTaskTitle = it\n                    },\n                    label = {\n                        Text(\"New Task\")\n                    },\n                    modifier = Modifier.weight(1f),\n                    singleLine = true\n                )\n\n                Button(\n                    onClick = {\n\n                        if (newTaskTitle.isNotBlank()) {\n\n                            viewModel.addTask(newTaskTitle)\n\n                            newTaskTitle = \"\"\n                        }\n                    }\n                ) {\n\n                    Text(\"Add\")\n                }\n            }\n\n            OutlinedTextField(\n                value = uiState.searchQuery,\n                onValueChange = viewModel::updateSearchQuery,\n                label = {\n                    Text(\"Search Tasks\")\n                },\n                modifier = Modifier.fillMaxWidth(),\n                singleLine = true\n            )\n\n            Row(\n                horizontalArrangement =\n                    Arrangement.spacedBy(8.dp)\n            ) {\n\n                TaskFilter.entries.forEach { filter -&gt;\n\n                    FilterChip(\n                        selected =\n                            uiState.selectedFilter == filter,\n                        onClick = {\n                            viewModel.updateFilter(filter)\n                        },\n                        label = {\n                            Text(filter.name)\n                        }\n                    )\n                }\n            }\n\n            if (uiState.tasks.isEmpty()) {\n\n                Box(\n                    modifier = Modifier\n                        .fillMaxWidth()\n                        .weight(1f),\n                    contentAlignment = Alignment.Center\n                ) {\n\n                    Text(\"No matching tasks\")\n                }\n\n            } else {\n\n                LazyColumn(\n                    modifier = Modifier.weight(1f),\n                    verticalArrangement =\n                        Arrangement.spacedBy(8.dp)\n                ) {\n\n                    items(\n                        items = uiState.tasks,\n                        key = { it.id }\n                    ) { task -&gt;\n\n                        TaskItem(\n                            task = task,\n                            onToggle = {\n                                viewModel.toggleTask(task.id)\n                            },\n                            onDelete = {\n                                viewModel.deleteTask(task.id)\n                            }\n                        )\n                    }\n                }\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">TaskScreen observes the ViewModel&#8217;s StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It forwards user actions to ViewModel functions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The new-task text field uses rememberSaveable because it is temporary UI element state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The search query and filter are owned by ViewModel and SavedStateHandle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This demonstrates using different state holders for different responsibilities.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. Step 9 \u2014 Create the Task Item<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Add the following composable to TaskScreen.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun TaskItem(\n    task: Task,\n    onToggle: () -&gt; Unit,\n    onDelete: () -&gt; Unit\n) {\n\n    Card(\n        modifier = Modifier.fillMaxWidth()\n    ) {\n\n        Row(\n            modifier = Modifier\n                .fillMaxWidth()\n                .padding(12.dp),\n            verticalAlignment =\n                Alignment.CenterVertically,\n            horizontalArrangement =\n                Arrangement.spacedBy(8.dp)\n        ) {\n\n            Checkbox(\n                checked = task.isCompleted,\n                onCheckedChange = {\n                    onToggle()\n                }\n            )\n\n            Text(\n                text = task.title,\n                modifier = Modifier.weight(1f),\n                style = MaterialTheme.typography.bodyLarge\n            )\n\n            TextButton(\n                onClick = onDelete\n            ) {\n\n                Text(\"Delete\")\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">TaskItem is a reusable stateless composable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It receives task information and callbacks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not depend directly on the ViewModel.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Step 10 \u2014 Create MainActivity<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>MainActivity.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.taskmanager\n\nimport android.os.Bundle\n\nimport androidx.activity.ComponentActivity\nimport androidx.activity.compose.setContent\n\nimport androidx.compose.material3.MaterialTheme\nimport androidx.compose.runtime.remember\n\nimport androidx.lifecycle.viewmodel.compose.viewModel\n\nimport com.example.taskmanager.data.InMemoryTaskRepository\nimport com.example.taskmanager.presentation.TaskScreen\nimport com.example.taskmanager.presentation.TaskViewModel\nimport com.example.taskmanager.presentation.TaskViewModelFactory\n\nclass MainActivity : ComponentActivity() {\n\n    private val repository = InMemoryTaskRepository()\n\n    override fun onCreate(\n        savedInstanceState: Bundle?\n    ) {\n\n        super.onCreate(savedInstanceState)\n\n        setContent {\n\n            MaterialTheme {\n\n                val factory = remember {\n                    TaskViewModelFactory(repository)\n                }\n\n                val taskViewModel: TaskViewModel =\n                    viewModel(factory = factory)\n\n                TaskScreen(\n                    viewModel = taskViewModel\n                )\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MainActivity provides the repository to the ViewModel factory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel is obtained through the Compose viewModel() function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For a production application, prefer an application-scoped repository or dependency injection container.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Activity-owned in-memory repository in this example is intentionally simple. It is recreated when the Activity is recreated, so its task data is not reliably preserved across configuration changes even though the ViewModel itself may survive.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Replace the repository with a properly scoped instance or Room-backed repository when persistence and stable ownership are required.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">25. Required Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a Jetpack Compose project and add the required libraries.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\n\n    implementation(\n        \"androidx.activity:activity-compose:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-viewmodel-ktx:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-viewmodel-compose:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-runtime-compose:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"org.jetbrains.kotlinx:kotlinx-coroutines-android:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.compose.material3:material3\"\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Replace placeholders with compatible stable versions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If your project uses the Compose BOM, use it to manage compatible Compose library versions.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">26. Expected Application UI<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Initial Screen<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|          Task Manager          |\n|                                |\n| Total: 0 | Active: 0 | Done: 0 |\n|                                |\n| &#91; New Task             ] &#91;Add] |\n|                                |\n| &#91; Search Tasks               ] |\n|                                |\n| &#91;ALL] &#91;ACTIVE] &#91;COMPLETED]     |\n|                                |\n|                                |\n|        No matching tasks       |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Tasks Added<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|          Task Manager          |\n|                                |\n| Total: 3 | Active: 2 | Done: 1 |\n|                                |\n| &#91; New Task             ] &#91;Add] |\n|                                |\n| &#91; Search Tasks               ] |\n|                                |\n| &#91;ALL] &#91;ACTIVE] &#91;COMPLETED]     |\n|                                |\n| &#91;\u2713] Learn Kotlin      &#91;Delete] |\n|                                |\n| &#91; ] Learn Compose     &#91;Delete] |\n|                                |\n| &#91; ] Learn StateFlow   &#91;Delete] |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Adding tasks updates repository state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel combines repository data with search and filter state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack Compose automatically renders the updated task list.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">27. How the Complete Application Works<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: User Adds a Task<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The user enters a task title and taps Add.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Compose Sends an Action<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">TaskScreen calls viewModel.addTask().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: ViewModel Calls Repository<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel launches a coroutine and requests the repository to add the task.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Repository Updates StateFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository publishes an updated task list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: ViewModel Combines State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">combine() recalculates filtered tasks and statistics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 6: Compose Receives Updated UI State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">collectAsStateWithLifecycle() observes the latest state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 7: UI Updates<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The new task appears in the list.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is a practical example of Unidirectional Data Flow.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">28. Handling Loading, Success, and Error States<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Some screens require mutually exclusive loading, success, and error states.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface UserUiState {\n\n    data object Loading : UserUiState\n\n    data class Success(\n        val users: List&lt;User&gt;\n    ) : UserUiState\n\n    data class Error(\n        val message: String\n    ) : UserUiState\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Compose Rendering<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>when (val state = uiState) {\n\n    UserUiState.Loading -&gt; {\n        CircularProgressIndicator()\n    }\n\n    is UserUiState.Success -&gt; {\n        UserList(state.users)\n    }\n\n    is UserUiState.Error -&gt; {\n        Text(state.message)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">When Should You Use a Data Class Instead?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use a data class when multiple conditions can occur simultaneously.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, cached content may remain visible while a refresh is running or an error banner is displayed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Choose a UI state model that represents the actual screen requirements.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">29. Handling One-Time UI Events<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android applications often need to handle events such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Showing a Snackbar<\/li>\n\n\n\n<li>Navigating after an action<\/li>\n\n\n\n<li>Displaying a confirmation message<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">There are multiple valid approaches.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For important user-visible outcomes, a reliable option is to represent the outcome in UI state and explicitly acknowledge it after handling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example UI State<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>data class FormUiState(\n    val isSaving: Boolean = false,\n    val saveCompleted: Boolean = false\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">ViewModel<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun onSaveCompleted() {\n\n    _uiState.update {\n        it.copy(saveCompleted = true)\n    }\n}\n\nfun onSaveResultHandled() {\n\n    _uiState.update {\n        it.copy(saveCompleted = false)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Compose<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>LaunchedEffect(uiState.saveCompleted) {\n\n    if (uiState.saveCompleted) {\n\n        snackbarHostState.showSnackbar(\n            \"Saved successfully\"\n        )\n\n        viewModel.onSaveResultHandled()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Event-handling strategy depends on delivery requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For critical operations, avoid relying on transient events that may be lost while the UI is inactive.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also ensure repeated operations have suitable identifiers or acknowledgements if the screen must distinguish multiple results.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">30. ViewModel with Repository Flow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In production applications, ViewModels frequently observe repository data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModel(\n    repository: ProductRepository\n) : ViewModel() {\n\n    val products: StateFlow&lt;List&lt;Product&gt;&gt; =\n        repository.observeProducts()\n            .stateIn(\n                scope = viewModelScope,\n                started =\n                    SharingStarted.WhileSubscribed(5_000),\n                initialValue = emptyList()\n            )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository exposes a Flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel converts it into a StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes the state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This pattern is useful with Room databases and offline-first repositories.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">31. Testing ViewModel and StateFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModels can be tested using Kotlin Coroutines testing utilities.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@OptIn(ExperimentalCoroutinesApi::class)\nclass CounterViewModelTest {\n\n    @get:Rule\n    val mainDispatcherRule = MainDispatcherRule()\n\n    @Test\n    fun `increment updates count`() = runTest {\n\n        val viewModel = CounterViewModel()\n\n        viewModel.increment()\n\n        assertEquals(\n            1,\n            viewModel.count.value\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies the ViewModel&#8217;s state update.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not require launching a Compose UI.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MainDispatcherRule should replace Dispatchers.Main with a test dispatcher and reset it after the test.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test also requires JUnit and kotlinx-coroutines-test dependencies.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">32. Testing StateFlow with Turbine<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Turbine is a library commonly used for testing Kotlin Flow emissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `counter emits updated value`() = runTest {\n\n    val viewModel = CounterViewModel()\n\n    viewModel.count.test {\n\n        assertEquals(0, awaitItem())\n\n        viewModel.increment()\n\n        assertEquals(1, awaitItem())\n\n        cancelAndIgnoreRemainingEvents()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test observes StateFlow emissions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It verifies both the initial and updated values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Required Library<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add a compatible version of the Turbine testing dependency.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>testImplementation(\n    \"app.cash.turbine:turbine:&lt;version&gt;\"\n)<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">33. StateFlow Performance Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">State management affects application responsiveness.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendations<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use immutable UI state models.<\/li>\n\n\n\n<li>Avoid unnecessary state updates.<\/li>\n\n\n\n<li>Keep large computations outside composables.<\/li>\n\n\n\n<li>Use derived state where appropriate.<\/li>\n\n\n\n<li>Avoid storing large datasets in SavedStateHandle.<\/li>\n\n\n\n<li>Use lifecycle-aware collection.<\/li>\n\n\n\n<li>Avoid unnecessary Flow collectors.<\/li>\n\n\n\n<li>Use stable item keys in LazyColumn.<\/li>\n\n\n\n<li>Avoid expensive transformations on the main thread.<\/li>\n\n\n\n<li>Use appropriate Flow operators for search and filtering.<\/li>\n\n\n\n<li>Profile before optimizing.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example Search Optimization<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For expensive searches, debounce user input before triggering repository operations.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>searchQuery\n    .debounce(300)\n    .distinctUntilChanged()\n    .flatMapLatest { query -&gt;\n        repository.searchProducts(query)\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">debounce() waits for a brief pause in typing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">flatMapLatest() switches to the latest search stream when the query changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This can reduce unnecessary work.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">34. Common ViewModel and StateFlow Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Exposing MutableStateFlow Publicly<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Expose read-only StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Storing Every UI Value in ViewModel<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep simple element-level state local when appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Using ViewModel as Permanent Storage<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Room or DataStore for durable information.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Collecting Flow Without Lifecycle Awareness<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use lifecycle-aware collection in Android UI components.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Performing Database Operations Directly in Composables<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use repositories and ViewModels.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Using SharedFlow for Critical Durable Outcomes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Consider state-based delivery with explicit acknowledgement.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Ignoring Process Death<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use SavedStateHandle for small restorable state and persistent storage for durable data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Creating Multiple Sources of Mutable UI State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Define clear state ownership.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Making ViewModels Too Large<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Move complex business logic into appropriate domain or data components.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Skipping Unit Tests<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test state transitions and failure scenarios.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">35. Production Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Follow these recommendations:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Keep ViewModels focused on presentation responsibilities.<\/li>\n\n\n\n<li>Expose immutable StateFlow.<\/li>\n\n\n\n<li>Use data classes or sealed types to model UI state clearly.<\/li>\n\n\n\n<li>Follow Unidirectional Data Flow.<\/li>\n\n\n\n<li>Hoist state appropriately.<\/li>\n\n\n\n<li>Use collectAsStateWithLifecycle().<\/li>\n\n\n\n<li>Use SavedStateHandle for small restorable values.<\/li>\n\n\n\n<li>Use Room or DataStore for persistent information.<\/li>\n\n\n\n<li>Keep repositories independent of composables.<\/li>\n\n\n\n<li>Handle coroutine cancellation correctly.<\/li>\n\n\n\n<li>Avoid unmanaged long-running coroutine scopes.<\/li>\n\n\n\n<li>Prefer constructor injection.<\/li>\n\n\n\n<li>Test ViewModel state transitions.<\/li>\n\n\n\n<li>Use fake repositories for unit tests.<\/li>\n\n\n\n<li>Avoid unnecessary recomposition work.<\/li>\n\n\n\n<li>Design event delivery according to reliability requirements.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">36. Quick Reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Concept<\/th><th>Purpose<\/th><\/tr><tr><td>ViewModel<\/td><td>Screen-level state holder<\/td><\/tr><tr><td>MutableStateFlow<\/td><td>Mutable observable state<\/td><\/tr><tr><td>StateFlow<\/td><td>Read-only observable state<\/td><\/tr><tr><td>SharedFlow<\/td><td>Configurable broadcast stream<\/td><\/tr><tr><td>SavedStateHandle<\/td><td>Small restorable state<\/td><\/tr><tr><td>remember<\/td><td>Composition-local state<\/td><\/tr><tr><td>rememberSaveable<\/td><td>Saveable UI element state<\/td><\/tr><tr><td>collectAsStateWithLifecycle()<\/td><td>Lifecycle-aware Flow collection<\/td><\/tr><tr><td>viewModelScope<\/td><td>ViewModel-owned coroutine scope<\/td><\/tr><tr><td>combine()<\/td><td>Combine multiple Flows<\/td><\/tr><tr><td>stateIn()<\/td><td>Convert Flow into StateFlow<\/td><\/tr><tr><td>SharingStarted.WhileSubscribed<\/td><td>Control upstream collection<\/td><\/tr><tr><td>UDF<\/td><td>Predictable state and action flow<\/td><\/tr><tr><td>Repository<\/td><td>Data access abstraction<\/td><\/tr><tr><td>Turbine<\/td><td>Flow testing library<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">37. Practical Exercises<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 1: Counter App<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Build a counter using ViewModel and StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Search Screen<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a search field backed by SavedStateHandle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 3: UI State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Implement loading, success, and error states.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 4: State Hoisting<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a reusable stateless TextField composable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: Filtered List<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use combine() to filter a list based on a selected category.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: Task Manager<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Build the complete Task Manager application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: Configuration Changes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Rotate the device and verify appropriate state behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: Process Recreation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test SavedStateHandle restoration using Android&#8217;s developer tools.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: Unit Testing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Write ViewModel tests using kotlinx-coroutines-test.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Persistent Storage<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Replace the in-memory task repository with Room.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">38. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is ViewModel in Android?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel is an Android Jetpack component that manages UI-related state and presentation logic.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why use StateFlow with ViewModel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow provides an observable current state that integrates naturally with Kotlin Coroutines and Jetpack Compose.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is StateFlow lifecycle-aware?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow itself is not lifecycle-aware.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use lifecycle-aware collection mechanisms such as collectAsStateWithLifecycle().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does ViewModel survive device rotation?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Typically yes, while its ViewModelStoreOwner is retained across the configuration change.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does ViewModel survive process death?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use SavedStateHandle or persistent storage for state that must be restored.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is SavedStateHandle?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">SavedStateHandle is a state holder that integrates with Android&#8217;s saved-state mechanism.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between StateFlow and SharedFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow represents a current state value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow provides a configurable stream for broadcasting values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should every Compose state be stored in ViewModel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep simple UI element state local when appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Unidirectional Data Flow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is an approach where user actions and state updates follow predictable paths.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can ViewModel be unit tested?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel logic can be tested with fake repositories and Kotlin Coroutines testing tools.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What We&#8217;ve Learned<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we explored:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Android UI state management<\/li>\n\n\n\n<li>ViewModel fundamentals<\/li>\n\n\n\n<li>ViewModel lifecycle<\/li>\n\n\n\n<li>StateFlow and MutableStateFlow<\/li>\n\n\n\n<li>StateFlow vs LiveData<\/li>\n\n\n\n<li>StateFlow vs SharedFlow<\/li>\n\n\n\n<li>Immutable UI state<\/li>\n\n\n\n<li>Unidirectional Data Flow<\/li>\n\n\n\n<li>State hoisting<\/li>\n\n\n\n<li>Lifecycle-aware Flow collection<\/li>\n\n\n\n<li>SavedStateHandle<\/li>\n\n\n\n<li>Configuration changes and process death<\/li>\n\n\n\n<li>Practical Task Manager application<\/li>\n\n\n\n<li>Repository integration<\/li>\n\n\n\n<li>One-time UI events<\/li>\n\n\n\n<li>ViewModel testing<\/li>\n\n\n\n<li>StateFlow performance<\/li>\n\n\n\n<li>Production best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel and StateFlow are important tools for building maintainable Android applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining Kotlin, Jetpack Compose, StateFlow, SavedStateHandle, and MVVM architecture, developers can create predictable UI state and clear application responsibilities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key is to define state ownership carefully and use the appropriate persistence mechanism for each type of information.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In our next tutorial:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Article 42 \u2014 Unidirectional Data Flow (UDF) in Android with Jetpack Compose: Events, State &amp; Effects<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll learn:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Unidirectional Data Flow fundamentals<\/li>\n\n\n\n<li>UI events and actions<\/li>\n\n\n\n<li>Immutable UI state<\/li>\n\n\n\n<li>ViewModel event handling<\/li>\n\n\n\n<li>Reducer-style state updates<\/li>\n\n\n\n<li>Side effects<\/li>\n\n\n\n<li>Navigation events<\/li>\n\n\n\n<li>Snackbar handling<\/li>\n\n\n\n<li>StateFlow integration<\/li>\n\n\n\n<li>Jetpack Compose integration<\/li>\n\n\n\n<li>MVI concepts<\/li>\n\n\n\n<li>Practical UDF mini-project<\/li>\n\n\n\n<li>Testing and production best practices<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Happy Coding!<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Continue learning modern Android development with <strong>Moiks Developer Blog<\/strong>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Managing UI state is one of the most important responsibilities in modern Android development. A simple Android application may contain only a few buttons and text fields. However, production applications often manage much more complex behavior. For example: Without proper state management, applications can become difficult to maintain and debug. Modern Android development provides powerful &#8230; <a title=\"Android ViewModel &#038; UI State Management with StateFlow and Jetpack Compose: Complete Guide\" class=\"read-more\" href=\"https:\/\/moiks.com\/blog\/android-viewmodel-ui-state-management-with-stateflow-and-jetpack-compose-complete-guide\/\" aria-label=\"Read more about Android ViewModel &#038; UI State Management with StateFlow and Jetpack Compose: Complete Guide\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":185,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0,"footnotes":""},"categories":[8,3,333],"tags":[],"class_list":["post-184","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-architecture","category-android-development","category-android-tutorials"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/184","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=184"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/184\/revisions"}],"predecessor-version":[{"id":186,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/184\/revisions\/186"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/185"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=184"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=184"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=184"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}