{"id":175,"date":"2026-10-19T09:30:00","date_gmt":"2026-10-19T09:30:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=175"},"modified":"2026-11-06T08:48:28","modified_gmt":"2026-11-06T08:48:28","slug":"mvvm-architecture-in-android-with-kotlin-jetpack-compose-complete-guide","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/mvvm-architecture-in-android-with-kotlin-jetpack-compose-complete-guide\/","title":{"rendered":"MVVM Architecture in Android with Kotlin &#038; Jetpack Compose: Complete Guide"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Building a simple Android application is relatively easy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, as applications grow, managing UI logic, business logic, networking, database operations, and application state becomes increasingly challenging.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Without a proper architecture, Android projects can quickly become difficult to maintain.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Developers may encounter problems such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Large Activity and Fragment classes<\/li>\n\n\n\n<li>Business logic mixed with UI code<\/li>\n\n\n\n<li>Duplicate code across screens<\/li>\n\n\n\n<li>Difficult unit testing<\/li>\n\n\n\n<li>Unpredictable UI state<\/li>\n\n\n\n<li>Tight coupling between components<\/li>\n\n\n\n<li>Complicated maintenance<\/li>\n\n\n\n<li>Poor scalability<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">To solve these problems, modern Android applications use architectural patterns.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One of the most widely used patterns is <strong>MVVM \u2014 Model-View-ViewModel<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">MVVM helps developers separate responsibilities, manage UI state, and build applications that are easier to test and maintain.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll learn how MVVM works and implement it using Kotlin, Jetpack Compose, ViewModel, StateFlow, and the Repository Pattern.<\/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 Android application architecture means<\/li>\n\n\n\n<li>Why architecture matters<\/li>\n\n\n\n<li>What MVVM is<\/li>\n\n\n\n<li>Model, View, and ViewModel responsibilities<\/li>\n\n\n\n<li>How MVVM works with Jetpack Compose<\/li>\n\n\n\n<li>Android ViewModel lifecycle<\/li>\n\n\n\n<li>Repository Pattern<\/li>\n\n\n\n<li>UI state management<\/li>\n\n\n\n<li>StateFlow integration<\/li>\n\n\n\n<li>Unidirectional Data Flow<\/li>\n\n\n\n<li>Separation of concerns<\/li>\n\n\n\n<li>Dependency injection concepts<\/li>\n\n\n\n<li>MVVM project structure<\/li>\n\n\n\n<li>Practical MVVM Android application<\/li>\n\n\n\n<li>Common architecture mistakes<\/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 Android Application Architecture?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Application architecture defines how different parts of an application are organized and communicate with one another.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A well-designed architecture separates responsibilities between components.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>UI components display information.<\/li>\n\n\n\n<li>ViewModels manage screen state and coordinate user actions.<\/li>\n\n\n\n<li>Repositories provide access to application data.<\/li>\n\n\n\n<li>Data sources communicate with APIs, databases, or other storage systems.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|          UI Layer              |\n|       Jetpack Compose          |\n+--------------------------------+\n                |\n                v\n+--------------------------------+\n|           ViewModel            |\n|       State Management         |\n+--------------------------------+\n                |\n                v\n+--------------------------------+\n|          Repository            |\n|        Data Operations         |\n+--------------------------------+\n                |\n                v\n+--------------------------------+\n|          Data Sources          |\n|       API \/ Room \/ Files       |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A good architecture improves:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Maintainability<\/li>\n\n\n\n<li>Testability<\/li>\n\n\n\n<li>Scalability<\/li>\n\n\n\n<li>Code readability<\/li>\n\n\n\n<li>Team collaboration<\/li>\n\n\n\n<li>Separation of responsibilities<\/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\">2. What Is MVVM Architecture?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">MVVM stands for:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Model \u2014 View \u2014 ViewModel<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is an architectural pattern that separates application data, presentation logic, and UI rendering.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MVVM Components<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Component<\/th><th>Responsibility<\/th><\/tr><tr><td>Model<\/td><td>Represents application data and domain concepts<\/td><\/tr><tr><td>View<\/td><td>Displays UI and forwards user interactions<\/td><\/tr><tr><td>ViewModel<\/td><td>Manages UI state and coordinates application operations<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">MVVM Architecture Diagram<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"> <code>         User Interaction\n                 |\n                 v\n+--------------------------------+\n|              View              |\n|         Jetpack Compose        |\n+--------------------------------+\n          |              ^\n          | Actions      | UI State\n          v              |\n+--------------------------------+\n|            ViewModel           |\n|       Presentation Logic       |\n+--------------------------------+\n                 |\n                 v\n+--------------------------------+\n|           Repository           |\n|          Data Access           |\n+--------------------------------+\n                 |\n                 v\n+--------------------------------+\n|           Data Sources         |\n|         API \/ Database         |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The View sends user actions to the ViewModel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel performs the necessary operations through repositories or use cases.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel then updates UI state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The View observes that state and renders the corresponding interface.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This creates a predictable flow 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\">3. Understanding the Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The Model represents application data and relevant domain concepts.<\/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\">A product may contain:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Product ID<\/li>\n\n\n\n<li>Product name<\/li>\n\n\n\n<li>Price<\/li>\n\n\n\n<li>Description<\/li>\n\n\n\n<li>Availability<\/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 Product(\n    val id: Int,\n    val name: String,\n    val price: Double,\n    val description: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Product class represents product information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not contain UI rendering logic.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep models focused on representing data or domain behavior.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid mixing Compose UI code into data models.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. Understanding the View<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In modern Android development, the View is commonly implemented using Jetpack Compose.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The View is responsible for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Displaying information<\/li>\n\n\n\n<li>Rendering UI state<\/li>\n\n\n\n<li>Receiving user input<\/li>\n\n\n\n<li>Forwarding user actions<\/li>\n\n\n\n<li>Showing loading indicators<\/li>\n\n\n\n<li>Displaying errors<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProductItem(\n    product: Product\n) {\n\n    Column(\n        modifier = Modifier.padding(16.dp)\n    ) {\n\n        Text(\n            text = product.name,\n            style = MaterialTheme.typography.titleMedium\n        )\n\n        Text(\n            text = \"\u20b9${product.price}\",\n            style = MaterialTheme.typography.bodyLarge\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 composable receives a Product and displays its information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not fetch data from a network or database.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep composables focused on UI responsibilities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid performing business logic or direct database operations inside composable functions.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Understanding the ViewModel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel is an Android Jetpack component designed to manage UI-related state and logic.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It can retain its instance across configuration changes, such as device rotation, while its 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>class ProductViewModel : ViewModel() {\n\n    private val _productName =\n        MutableStateFlow(\"Android Phone\")\n\n    val productName: StateFlow&lt;String&gt; =\n        _productName.asStateFlow()\n\n    fun updateProductName(name: String) {\n\n        _productName.value = name\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 the state changes, Jetpack Compose can update the interface automatically.<\/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\">Use SavedStateHandle or persistent storage for information that must be restored.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Why Use ViewModel Instead of Activity?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Traditional Android applications sometimes place most application logic inside Activities.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Problematic Approach<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class MainActivity : ComponentActivity() {\n\n    \/\/ UI setup\n    \/\/ API requests\n    \/\/ Database operations\n    \/\/ State management\n    \/\/ Business logic\n    \/\/ Navigation handling\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This creates a class with too many responsibilities.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MVVM Approach<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>MainActivity\n    |\n    v\nJetpack Compose Screen\n    |\n    v\nProductViewModel\n    |\n    v\nProductRepository<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Smaller UI components<\/li>\n\n\n\n<li>Better separation of concerns<\/li>\n\n\n\n<li>Easier unit testing<\/li>\n\n\n\n<li>Clearer state ownership<\/li>\n\n\n\n<li>More maintainable code<\/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\">7. Understanding the Repository Pattern<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A Repository provides a consistent interface for accessing application data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It can coordinate multiple data sources.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>REST APIs<\/li>\n\n\n\n<li>Room databases<\/li>\n\n\n\n<li>DataStore<\/li>\n\n\n\n<li>Local files<\/li>\n\n\n\n<li>In-memory caches<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Repository Interface<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>interface ProductRepository {\n\n    suspend fun getProducts(): List&lt;Product&gt;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Repository Implementation<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductRepositoryImpl : ProductRepository {\n\n    override suspend fun getProducts(): List&lt;Product&gt; {\n\n        return listOf(\n            Product(\n                id = 1,\n                name = \"Android Phone\",\n                price = 19999.0,\n                description = \"Modern Android smartphone\"\n            ),\n            Product(\n                id = 2,\n                name = \"Smart Watch\",\n                price = 4999.0,\n                description = \"Fitness and activity tracker\"\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 ViewModel depends on ProductRepository rather than a particular implementation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes it easier to replace the data source.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Better testability<\/li>\n\n\n\n<li>Flexible data sources<\/li>\n\n\n\n<li>Reduced coupling<\/li>\n\n\n\n<li>Centralized data access<\/li>\n\n\n\n<li>Easier future expansion<\/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\">8. Understanding UI State in MVVM<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">UI state describes what the screen should display.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a product screen may have three states:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Loading<\/li>\n\n\n\n<li>Success<\/li>\n\n\n\n<li>Error<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface ProductUiState {\n\n    data object Loading : ProductUiState\n\n    data class Success(\n        val products: List&lt;Product&gt;\n    ) : ProductUiState\n\n    data class Error(\n        val message: String\n    ) : ProductUiState\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Using a sealed interface makes the possible states explicit.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack Compose can render each state separately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Predictable UI behavior<\/li>\n\n\n\n<li>Easier debugging<\/li>\n\n\n\n<li>Clear error handling<\/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\">9. StateFlow in MVVM Architecture<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow is commonly used to expose observable UI state from ViewModel.<\/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    private val repository: ProductRepository\n) : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow&lt;ProductUiState&gt;(\n            ProductUiState.Loading\n        )\n\n    val uiState: StateFlow&lt;ProductUiState&gt; =\n        _uiState.asStateFlow()\n\n    fun loadProducts() {\n\n        viewModelScope.launch {\n\n            try {\n\n                val products = repository.getProducts()\n\n                _uiState.value =\n                    ProductUiState.Success(products)\n\n            } catch (exception: CancellationException) {\n\n                throw exception\n\n            } catch (exception: Exception) {\n\n                _uiState.value =\n                    ProductUiState.Error(\n                        \"Unable to load products\"\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\">The ViewModel requests data from the repository.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It updates StateFlow based on the result.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes the latest state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep MutableStateFlow private and expose StateFlow publicly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. What Is Unidirectional Data Flow?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Unidirectional Data Flow, or UDF, means information moves through the application in a predictable direction.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">UDF Diagram<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"> <code>       User Action\n             |\n             v\n       Jetpack Compose\n             |\n             v\n          ViewModel\n             |\n             v\n          Repository\n             |\n             v\n         Data Result\n             |\n             v\n        ViewModel State\n             |\n             v\n       Jetpack Compose<\/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 actions to the ViewModel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel processes those actions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel publishes updated state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI renders that 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 state changes<\/li>\n\n\n\n<li>Easier debugging<\/li>\n\n\n\n<li>Better separation of concerns<\/li>\n\n\n\n<li>Reduced unexpected behavior<\/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\">11. State Hoisting in Jetpack Compose<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">State hoisting moves state ownership to an appropriate 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 SearchField(\n    query: String,\n    onQueryChange: (String) -&gt; Unit\n) {\n\n    OutlinedTextField(\n        value = query,\n        onValueChange = onQueryChange,\n        label = {\n            Text(\"Search Products\")\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\">SearchField does not own the query state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It receives the current value and a callback.<\/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 testing<\/li>\n\n\n\n<li>Clear state ownership<\/li>\n\n\n\n<li>Better integration with ViewModel<\/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 detail needs to be stored 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\">12. MVVM vs MVC vs MVP<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android developers may encounter several architectural patterns.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>MVC<\/th><th>MVP<\/th><th>MVVM<\/th><\/tr><tr><td>Main components<\/td><td>Model, View, Controller<\/td><td>Model, View, Presenter<\/td><td>Model, View, ViewModel<\/td><\/tr><tr><td>UI state management<\/td><td>Varies<\/td><td>Presenter-driven<\/td><td>ViewModel-driven<\/td><\/tr><tr><td>Jetpack Compose integration<\/td><td>Possible<\/td><td>Possible<\/td><td>Natural fit<\/td><\/tr><tr><td>Android Jetpack ViewModel<\/td><td>Not required<\/td><td>Not required<\/td><td>Commonly used<\/td><\/tr><tr><td>Testability<\/td><td>Depends on implementation<\/td><td>Generally good<\/td><td>Generally good<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Which Architecture Should You Choose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For modern Android applications using Kotlin and Jetpack Compose, MVVM with Unidirectional Data Flow is a practical and widely used choice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, architecture quality depends on implementation, not only the pattern name.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">Practical Android Mini-Project: Product Catalog Using MVVM<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s build a complete Android mini-project.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Our application will display a list of products using MVVM architecture.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Product list<\/li>\n\n\n\n<li>Loading indicator<\/li>\n\n\n\n<li>Error state<\/li>\n\n\n\n<li>Retry functionality<\/li>\n\n\n\n<li>Repository abstraction<\/li>\n\n\n\n<li>ViewModel<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>Jetpack Compose UI<\/li>\n\n\n\n<li>Manual refresh<\/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>Kotlin Coroutines<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>MVVM<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial uses a local in-memory repository to keep the focus on architecture.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Recommended Project Structure<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>app\/\n\u2502\n\u2514\u2500\u2500 src\/main\/java\/com\/example\/mvvmapp\/\n    \u2502\n    \u251c\u2500\u2500 data\/\n    \u2502   \u2514\u2500\u2500 repository\/\n    \u2502       \u251c\u2500\u2500 ProductRepository.kt\n    \u2502       \u2514\u2500\u2500 ProductRepositoryImpl.kt\n    \u2502\n    \u251c\u2500\u2500 model\/\n    \u2502   \u2514\u2500\u2500 Product.kt\n    \u2502\n    \u251c\u2500\u2500 ui\/\n    \u2502   \u2514\u2500\u2500 product\/\n    \u2502       \u251c\u2500\u2500 ProductUiState.kt\n    \u2502       \u251c\u2500\u2500 ProductViewModel.kt\n    \u2502       \u251c\u2500\u2500 ProductViewModelFactory.kt\n    \u2502       \u2514\u2500\u2500 ProductScreen.kt\n    \u2502\n    \u2514\u2500\u2500 MainActivity.kt<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each package has a clear responsibility.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The model package contains data models.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The repository package handles data access.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI package contains presentation logic and Compose screens.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Create the Product Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create Product.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data class Product(\n    val id: Int,\n    val name: String,\n    val price: Double,\n    val description: String\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\">15. Create the Repository Interface<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create ProductRepository.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>interface ProductRepository {\n\n    suspend fun getProducts(): List&lt;Product&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\">16. Create the Repository Implementation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create ProductRepositoryImpl.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductRepositoryImpl : ProductRepository {\n\n    override suspend fun getProducts(): List&lt;Product&gt; {\n\n        delay(800)\n\n        return listOf(\n            Product(\n                id = 1,\n                name = \"Android Phone\",\n                price = 19999.0,\n                description = \"Powerful Android smartphone\"\n            ),\n            Product(\n                id = 2,\n                name = \"Bluetooth Speaker\",\n                price = 2499.0,\n                description = \"Portable wireless speaker\"\n            ),\n            Product(\n                id = 3,\n                name = \"Smart Watch\",\n                price = 4999.0,\n                description = \"Health and activity tracking\"\n            ),\n            Product(\n                id = 4,\n                name = \"Wireless Headphones\",\n                price = 2999.0,\n                description = \"Comfortable wireless audio\"\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 simulates a data-loading operation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The delay represents asynchronous work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No network or database dependency is required.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Create the UI State<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create ProductUiState.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface ProductUiState {\n\n    data object Loading : ProductUiState\n\n    data class Success(\n        val products: List&lt;Product&gt;\n    ) : ProductUiState\n\n    data class Error(\n        val message: String\n    ) : ProductUiState\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\">18. Create the ViewModel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create ProductViewModel.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModel(\n    private val repository: ProductRepository\n) : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow&lt;ProductUiState&gt;(\n            ProductUiState.Loading\n        )\n\n    val uiState: StateFlow&lt;ProductUiState&gt; =\n        _uiState.asStateFlow()\n\n    private var loadJob: Job? = null\n\n    init {\n        loadProducts()\n    }\n\n    fun loadProducts() {\n\n        loadJob?.cancel()\n\n        loadJob = viewModelScope.launch {\n\n            _uiState.value = ProductUiState.Loading\n\n            try {\n\n                val products = repository.getProducts()\n\n                _uiState.value =\n                    ProductUiState.Success(products)\n\n            } catch (exception: CancellationException) {\n\n                throw exception\n\n            } catch (exception: Exception) {\n\n                _uiState.value =\n                    ProductUiState.Error(\n                        \"Unable to load products. Please try again.\"\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\">The ViewModel coordinates data loading.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not know how the repository obtains products.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It exposes a single observable UI state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel also prevents overlapping loads by cancelling the previous job.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Create the ViewModel Factory<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create ProductViewModelFactory.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModelFactory(\n    private val repository: ProductRepository\n) : ViewModelProvider.Factory {\n\n    override fun &lt;T : ViewModel&gt; create(\n        modelClass: Class&lt;T&gt;\n    ): T {\n\n        if (\n            modelClass.isAssignableFrom(\n                ProductViewModel::class.java\n            )\n        ) {\n\n            @Suppress(\"UNCHECKED_CAST\")\n            return ProductViewModel(repository) 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 dependency to the ViewModel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is a simple example of constructor-based dependency injection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In larger applications, Hilt can automate dependency creation.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Create the Product Screen<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create ProductScreen.kt.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProductScreen(\n    viewModel: ProductViewModel\n) {\n\n    val uiState by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    ProductContent(\n        uiState = uiState,\n        onRetry = viewModel::loadProducts\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ProductScreen acts as a route-level composable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It connects the ViewModel to the UI.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The actual UI rendering is delegated to ProductContent.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes the content composable easier to preview and test.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Create the Stateless UI Content<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProductContent(\n    uiState: ProductUiState,\n    onRetry: () -&gt; Unit\n) {\n\n    Scaffold(\n        topBar = {\n\n            TopAppBar(\n                title = {\n                    Text(\"MVVM Product Catalog\")\n                }\n            )\n        }\n    ) { paddingValues -&gt;\n\n        Box(\n            modifier = Modifier\n                .fillMaxSize()\n                .padding(paddingValues)\n        ) {\n\n            when (uiState) {\n\n                ProductUiState.Loading -&gt; {\n\n                    CircularProgressIndicator(\n                        modifier = Modifier.align(\n                            Alignment.Center\n                        )\n                    )\n                }\n\n                is ProductUiState.Success -&gt; {\n\n                    Column {\n\n                        Button(\n                            onClick = onRetry,\n                            modifier = Modifier.padding(16.dp)\n                        ) {\n\n                            Text(\"Refresh Products\")\n                        }\n\n                        LazyColumn(\n                            contentPadding = PaddingValues(16.dp),\n                            verticalArrangement =\n                                Arrangement.spacedBy(12.dp)\n                        ) {\n\n                            items(\n                                items = uiState.products,\n                                key = { it.id }\n                            ) { product -&gt;\n\n                                ProductCard(product)\n                            }\n                        }\n                    }\n                }\n\n                is ProductUiState.Error -&gt; {\n\n                    Column(\n                        modifier = Modifier.align(\n                            Alignment.Center\n                        ),\n                        horizontalAlignment =\n                            Alignment.CenterHorizontally,\n                        verticalArrangement =\n                            Arrangement.spacedBy(16.dp)\n                    ) {\n\n                        Text(\n                            text = uiState.message,\n                            color = MaterialTheme.colorScheme.error\n                        )\n\n                        Button(\n                            onClick = onRetry\n                        ) {\n\n                            Text(\"Retry\")\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\">ProductContent receives immutable UI state and a callback.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not depend directly on ViewModel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This follows the principles of state hoisting and separation of concerns.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Create the Product Card<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ProductCard(\n    product: Product\n) {\n\n    Card(\n        modifier = Modifier.fillMaxWidth()\n    ) {\n\n        Column(\n            modifier = Modifier.padding(16.dp),\n            verticalArrangement =\n                Arrangement.spacedBy(8.dp)\n        ) {\n\n            Text(\n                text = product.name,\n                style = MaterialTheme.typography.titleMedium\n            )\n\n            Text(\n                text = product.description,\n                style = MaterialTheme.typography.bodyMedium\n            )\n\n            Text(\n                text = \"\u20b9${product.price}\",\n                style = MaterialTheme.typography.titleSmall,\n                color = MaterialTheme.colorScheme.primary\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\">ProductCard only renders product information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It can be reused in other screens without depending on ViewModel or repository classes.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. Create MainActivity<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class MainActivity : ComponentActivity() {\n\n    override fun onCreate(\n        savedInstanceState: Bundle?\n    ) {\n\n        super.onCreate(savedInstanceState)\n\n        setContent {\n\n            MaterialTheme {\n\n                val viewModel: ProductViewModel =\n                    viewModel(\n                        factory = ProductViewModelFactory(\n                            ProductRepositoryImpl()\n                        )\n                    )\n\n                ProductScreen(\n                    viewModel = viewModel\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 sets the Compose content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel is obtained using a factory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The repository is provided through constructor injection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a larger application, dependency creation should be moved into an application-level dependency injection setup.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Required Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Add the following dependencies to your app module if they are not already included.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\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 version placeholders with compatible stable versions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If your project uses the Compose BOM, keep Compose library versions managed through that BOM.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Material 3 TopAppBar APIs may require opting into ExperimentalMaterial3Api depending on the library version.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use the annotation where required:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@OptIn(ExperimentalMaterial3Api::class)<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">25. Expected UI \u2014 Loading<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|       MVVM Product Catalog     |\n|                                |\n|                                |\n|              \u25cb                 |\n|                                |\n|        Loading products...     |\n|                                |\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\">26. Expected UI \u2014 Success<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|       MVVM Product Catalog     |\n|                                |\n|      &#91; Refresh Products ]      |\n|                                |\n| +----------------------------+ |\n| | Android Phone              | |\n| | Powerful Android smartphone| |\n| | \u20b919999.0                   | |\n| +----------------------------+ |\n|                                |\n| +----------------------------+ |\n| | Bluetooth Speaker          | |\n| | Portable wireless speaker  | |\n| | \u20b92499.0                    | |\n| +----------------------------+ |\n|                                |\n| +----------------------------+ |\n| | Smart Watch                | |\n| | Health and activity        | |\n| | tracking                   | |\n| | \u20b94999.0                    | |\n| +----------------------------+ |\n|                                |\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\">27. Expected UI \u2014 Error<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|       MVVM Product Catalog     |\n|                                |\n|                                |\n|  Unable to load products.      |\n|       Please try again.        |\n|                                |\n|            &#91; Retry ]           |\n|                                |\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\">28. How the Complete MVVM Application Works<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: MainActivity Starts<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MainActivity creates the Compose UI and obtains the ViewModel.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: ViewModel Initializes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel begins loading products.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: StateFlow Publishes Loading<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI displays a progress indicator.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Repository Loads Data<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository returns the product list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: ViewModel Publishes Success<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow receives ProductUiState.Success.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 6: Compose Recomposition<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes the new state and displays the products.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 7: User Refreshes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI calls the ViewModel&#8217;s loadProducts() function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 8: ViewModel Reloads Data<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The loading process begins again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This demonstrates a complete 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\">29. How to Test MVVM Architecture<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">MVVM improves testability because the ViewModel can be tested without launching the full Android UI.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Fake Repository<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class FakeProductRepository : ProductRepository {\n\n    override suspend fun getProducts(): List&lt;Product&gt; {\n\n        return listOf(\n            Product(\n                id = 1,\n                name = \"Test Product\",\n                price = 100.0,\n                description = \"Testing MVVM\"\n            )\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">ViewModel Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The following test uses the MainDispatcherRule introduced in our previous Kotlin Flow testing tutorial.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@OptIn(ExperimentalCoroutinesApi::class)\nclass ProductViewModelTest {\n\n    @get:Rule\n    val mainDispatcherRule = MainDispatcherRule()\n\n    @Test\n    fun `products load successfully`() = runTest {\n\n        val repository = FakeProductRepository()\n\n        val viewModel = ProductViewModel(repository)\n\n        advanceUntilIdle()\n\n        val state = viewModel.uiState.value\n\n        assertTrue(\n            state is ProductUiState.Success\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 uses a fake repository.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No real network request is required.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies the ViewModel&#8217;s final 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\">30. MVVM Architecture with Dependency Injection<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dependency injection allows dependencies to be provided from outside a class.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Without Dependency Injection<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModel : ViewModel() {\n\n    private val repository =\n        ProductRepositoryImpl()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">With Constructor Injection<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModel(\n    private val repository: ProductRepository\n) : ViewModel()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Reduced coupling<\/li>\n\n\n\n<li>Easier testing<\/li>\n\n\n\n<li>Flexible implementations<\/li>\n\n\n\n<li>Better scalability<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Production Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Hilt when dependency management becomes complex.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, understanding manual dependency injection first is valuable.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">31. MVVM Architecture 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 composables focused on UI rendering.<\/li>\n\n\n\n<li>Store screen state in ViewModel when appropriate.<\/li>\n\n\n\n<li>Expose immutable StateFlow.<\/li>\n\n\n\n<li>Use repositories for data access.<\/li>\n\n\n\n<li>Prefer constructor injection.<\/li>\n\n\n\n<li>Use Unidirectional Data Flow.<\/li>\n\n\n\n<li>Keep UI state models explicit.<\/li>\n\n\n\n<li>Use lifecycle-aware Flow collection.<\/li>\n\n\n\n<li>Avoid Android Context references in ordinary ViewModels.<\/li>\n\n\n\n<li>Keep domain and data responsibilities separate.<\/li>\n\n\n\n<li>Handle coroutine cancellation correctly.<\/li>\n\n\n\n<li>Avoid performing API calls directly inside composables.<\/li>\n\n\n\n<li>Write ViewModel unit tests.<\/li>\n\n\n\n<li>Avoid unnecessary abstraction layers.<\/li>\n\n\n\n<li>Organize packages by feature as applications grow.<\/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\">32. Common MVVM Architecture Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Putting Business Logic Inside Composables<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Composables should focus on rendering UI and forwarding interactions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Creating Repositories Directly Inside ViewModel<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer constructor injection.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: 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 4: Using ViewModel for Every Small UI State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Temporary UI details can remain inside composables when appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Making ViewModels Too Large<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Split responsibilities into repositories and use cases when complexity grows.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Mixing Data Access with UI Rendering<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep database and network operations outside composables.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Ignoring Cancellation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Preserve CancellationException.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Creating Too Many Layers<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not introduce unnecessary abstractions into simple applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Using Unmanaged CoroutineScopes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer lifecycle-aware coroutine ownership.<\/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 ViewModel behavior with fake repositories.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">33. MVVM Architecture Quick Reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Component<\/th><th>Responsibility<\/th><\/tr><tr><td>Model<\/td><td>Application data<\/td><\/tr><tr><td>View<\/td><td>UI rendering<\/td><\/tr><tr><td>ViewModel<\/td><td>UI state and presentation logic<\/td><\/tr><tr><td>Repository<\/td><td>Data access abstraction<\/td><\/tr><tr><td>StateFlow<\/td><td>Observable UI state<\/td><\/tr><tr><td>MutableStateFlow<\/td><td>Mutable state holder<\/td><\/tr><tr><td>viewModelScope<\/td><td>ViewModel-owned coroutines<\/td><\/tr><tr><td>collectAsStateWithLifecycle()<\/td><td>Lifecycle-aware state collection<\/td><\/tr><tr><td>UDF<\/td><td>Predictable data and action flow<\/td><\/tr><tr><td>Dependency Injection<\/td><td>External dependency provisioning<\/td><\/tr><tr><td>Hilt<\/td><td>Android dependency injection framework<\/td><\/tr><tr><td>SavedStateHandle<\/td><td>Saved state support in ViewModel<\/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\">34. Practical Exercises<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 1: Simple MVVM<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a counter application using ViewModel and StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Repository Pattern<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a repository interface that returns a list of users.<\/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 TextField composable with value and onValueChange parameters.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: Manual Dependency Injection<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a ViewModel factory.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: Product Catalog<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Build the complete product catalog mini-project.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: Search Feature<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add product search functionality.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: Error Handling<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Simulate repository failures and display an error screen.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: Unit Testing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test the ViewModel using a fake repository.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Architecture Improvement<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Separate the project into data, domain, and UI packages.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">35. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is MVVM architecture in Android?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MVVM stands for Model-View-ViewModel. It separates application data, UI rendering, and presentation logic.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why is MVVM used in Android?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MVVM improves maintainability, testability, separation of concerns, and state management.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is MVVM suitable for Jetpack Compose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. MVVM works naturally with Jetpack Compose and StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the role of ViewModel?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel manages UI-related state and coordinates operations required by the screen.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the Repository Pattern?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Repository Pattern provides an abstraction for accessing application data.<\/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\">UDF is an approach where UI actions and state updates move through predictable paths.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should every Android application use MVVM?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Not necessarily. Architecture should match application complexity and requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, MVVM is a practical choice for many modern Android applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between ViewModel and Repository?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel manages presentation state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Repository provides data access.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is Hilt required for MVVM?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. MVVM can use manual dependency injection or other dependency injection frameworks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can MVVM be unit tested?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. ViewModels can be tested using fake repositories and coroutine testing utilities.<\/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 application architecture<\/li>\n\n\n\n<li>MVVM fundamentals<\/li>\n\n\n\n<li>Model responsibilities<\/li>\n\n\n\n<li>View responsibilities<\/li>\n\n\n\n<li>ViewModel responsibilities<\/li>\n\n\n\n<li>Repository Pattern<\/li>\n\n\n\n<li>UI state management<\/li>\n\n\n\n<li>StateFlow integration<\/li>\n\n\n\n<li>Unidirectional Data Flow<\/li>\n\n\n\n<li>State hoisting<\/li>\n\n\n\n<li>Dependency injection concepts<\/li>\n\n\n\n<li>Jetpack Compose integration<\/li>\n\n\n\n<li>Practical product catalog application<\/li>\n\n\n\n<li>ViewModel unit testing<\/li>\n\n\n\n<li>Common mistakes and best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">MVVM is a powerful architectural pattern for building maintainable Android applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining Kotlin, Jetpack Compose, ViewModel, StateFlow, and repositories, developers can create applications with clear responsibilities and predictable state management.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These concepts form the foundation for more advanced Android architecture patterns, including Clean Architecture, domain layers, use cases, and multi-module applications.<\/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, we&#8217;ll explore:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Article 39 \u2014 Clean Architecture in Android with Kotlin &amp; Jetpack Compose: Data, Domain &amp; Presentation Layers<\/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>What Clean Architecture is<\/li>\n\n\n\n<li>Why Clean Architecture matters<\/li>\n\n\n\n<li>Data layer<\/li>\n\n\n\n<li>Domain layer<\/li>\n\n\n\n<li>Presentation layer<\/li>\n\n\n\n<li>Dependency Rule<\/li>\n\n\n\n<li>Repository interfaces<\/li>\n\n\n\n<li>Use cases<\/li>\n\n\n\n<li>Dependency injection<\/li>\n\n\n\n<li>StateFlow integration<\/li>\n\n\n\n<li>Jetpack Compose UI<\/li>\n\n\n\n<li>Practical Clean Architecture mini-project<\/li>\n\n\n\n<li>Common mistakes<\/li>\n\n\n\n<li>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\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Master MVVM architecture in Android with Kotlin and Jetpack Compose. Learn Model, View, ViewModel, Repository Pattern, StateFlow, Unidirectional Data Flow, and build a practical Android application.<\/p>\n","protected":false},"author":1,"featured_media":176,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0,"footnotes":""},"categories":[3,333,8],"tags":[],"class_list":["post-175","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-development","category-android-tutorials","category-android-architecture"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/175","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=175"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/175\/revisions"}],"predecessor-version":[{"id":177,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/175\/revisions\/177"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/176"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=175"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=175"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=175"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}