MVVM Architecture in Android with Kotlin & Jetpack Compose: Complete Guide

Building a simple Android application is relatively easy.

However, as applications grow, managing UI logic, business logic, networking, database operations, and application state becomes increasingly challenging.

Without a proper architecture, Android projects can quickly become difficult to maintain.

Developers may encounter problems such as:

  • Large Activity and Fragment classes
  • Business logic mixed with UI code
  • Duplicate code across screens
  • Difficult unit testing
  • Unpredictable UI state
  • Tight coupling between components
  • Complicated maintenance
  • Poor scalability

To solve these problems, modern Android applications use architectural patterns.

One of the most widely used patterns is MVVM — Model-View-ViewModel.

MVVM helps developers separate responsibilities, manage UI state, and build applications that are easier to test and maintain.

In this tutorial, we’ll learn how MVVM works and implement it using Kotlin, Jetpack Compose, ViewModel, StateFlow, and the Repository Pattern.


What You’ll Learn

By the end of this tutorial, you’ll understand:

  • What Android application architecture means
  • Why architecture matters
  • What MVVM is
  • Model, View, and ViewModel responsibilities
  • How MVVM works with Jetpack Compose
  • Android ViewModel lifecycle
  • Repository Pattern
  • UI state management
  • StateFlow integration
  • Unidirectional Data Flow
  • Separation of concerns
  • Dependency injection concepts
  • MVVM project structure
  • Practical MVVM Android application
  • Common architecture mistakes
  • Production best practices

Let’s begin!


1. What Is Android Application Architecture?

Application architecture defines how different parts of an application are organized and communicate with one another.

A well-designed architecture separates responsibilities between components.

For example:

  • UI components display information.
  • ViewModels manage screen state and coordinate user actions.
  • Repositories provide access to application data.
  • Data sources communicate with APIs, databases, or other storage systems.

Example Architecture

+--------------------------------+
|          UI Layer              |
|       Jetpack Compose          |
+--------------------------------+
                |
                v
+--------------------------------+
|           ViewModel            |
|       State Management         |
+--------------------------------+
                |
                v
+--------------------------------+
|          Repository            |
|        Data Operations         |
+--------------------------------+
                |
                v
+--------------------------------+
|          Data Sources          |
|       API / Room / Files       |
+--------------------------------+

Benefits

A good architecture improves:

  • Maintainability
  • Testability
  • Scalability
  • Code readability
  • Team collaboration
  • Separation of responsibilities

2. What Is MVVM Architecture?

MVVM stands for:

Model — View — ViewModel

It is an architectural pattern that separates application data, presentation logic, and UI rendering.

MVVM Components

ComponentResponsibility
ModelRepresents application data and domain concepts
ViewDisplays UI and forwards user interactions
ViewModelManages UI state and coordinates application operations

MVVM Architecture Diagram

          User Interaction
                 |
                 v
+--------------------------------+
|              View              |
|         Jetpack Compose        |
+--------------------------------+
          |              ^
          | Actions      | UI State
          v              |
+--------------------------------+
|            ViewModel           |
|       Presentation Logic       |
+--------------------------------+
                 |
                 v
+--------------------------------+
|           Repository           |
|          Data Access           |
+--------------------------------+
                 |
                 v
+--------------------------------+
|           Data Sources         |
|         API / Database         |
+--------------------------------+

Explanation

The View sends user actions to the ViewModel.

The ViewModel performs the necessary operations through repositories or use cases.

The ViewModel then updates UI state.

The View observes that state and renders the corresponding interface.

This creates a predictable flow of information.


3. Understanding the Model

The Model represents application data and relevant domain concepts.

For example, consider a shopping application.

A product may contain:

  • Product ID
  • Product name
  • Price
  • Description
  • Availability

Example

data class Product(
    val id: Int,
    val name: String,
    val price: Double,
    val description: String
)

Explanation

The Product class represents product information.

It does not contain UI rendering logic.

Best Practice

Keep models focused on representing data or domain behavior.

Avoid mixing Compose UI code into data models.


4. Understanding the View

In modern Android development, the View is commonly implemented using Jetpack Compose.

The View is responsible for:

  • Displaying information
  • Rendering UI state
  • Receiving user input
  • Forwarding user actions
  • Showing loading indicators
  • Displaying errors

Example

@Composable
fun ProductItem(
    product: Product
) {

    Column(
        modifier = Modifier.padding(16.dp)
    ) {

        Text(
            text = product.name,
            style = MaterialTheme.typography.titleMedium
        )

        Text(
            text = "₹${product.price}",
            style = MaterialTheme.typography.bodyLarge
        )
    }
}

Explanation

The composable receives a Product and displays its information.

It does not fetch data from a network or database.

Best Practice

Keep composables focused on UI responsibilities.

Avoid performing business logic or direct database operations inside composable functions.


5. Understanding the ViewModel

ViewModel is an Android Jetpack component designed to manage UI-related state and logic.

It can retain its instance across configuration changes, such as device rotation, while its ViewModelStoreOwner remains active.

Example

class ProductViewModel : ViewModel() {

    private val _productName =
        MutableStateFlow("Android Phone")

    val productName: StateFlow<String> =
        _productName.asStateFlow()

    fun updateProductName(name: String) {

        _productName.value = name
    }
}

Explanation

The ViewModel owns the mutable state.

The UI observes a read-only StateFlow.

When the state changes, Jetpack Compose can update the interface automatically.

Important

ViewModel does not automatically preserve all in-memory state after process death.

Use SavedStateHandle or persistent storage for information that must be restored.


6. Why Use ViewModel Instead of Activity?

Traditional Android applications sometimes place most application logic inside Activities.

Problematic Approach

class MainActivity : ComponentActivity() {

    // UI setup
    // API requests
    // Database operations
    // State management
    // Business logic
    // Navigation handling
}

This creates a class with too many responsibilities.

MVVM Approach

MainActivity
    |
    v
Jetpack Compose Screen
    |
    v
ProductViewModel
    |
    v
ProductRepository

Benefits

  • Smaller UI components
  • Better separation of concerns
  • Easier unit testing
  • Clearer state ownership
  • More maintainable code

7. Understanding the Repository Pattern

A Repository provides a consistent interface for accessing application data.

It can coordinate multiple data sources.

For example:

  • REST APIs
  • Room databases
  • DataStore
  • Local files
  • In-memory caches

Repository Interface

interface ProductRepository {

    suspend fun getProducts(): List<Product>
}

Repository Implementation

class ProductRepositoryImpl : ProductRepository {

    override suspend fun getProducts(): List<Product> {

        return listOf(
            Product(
                id = 1,
                name = "Android Phone",
                price = 19999.0,
                description = "Modern Android smartphone"
            ),
            Product(
                id = 2,
                name = "Smart Watch",
                price = 4999.0,
                description = "Fitness and activity tracker"
            )
        )
    }
}

Explanation

The ViewModel depends on ProductRepository rather than a particular implementation.

This makes it easier to replace the data source.

Benefits

  • Better testability
  • Flexible data sources
  • Reduced coupling
  • Centralized data access
  • Easier future expansion

8. Understanding UI State in MVVM

UI state describes what the screen should display.

For example, a product screen may have three states:

  1. Loading
  2. Success
  3. Error

Example

sealed interface ProductUiState {

    data object Loading : ProductUiState

    data class Success(
        val products: List<Product>
    ) : ProductUiState

    data class Error(
        val message: String
    ) : ProductUiState
}

Explanation

Using a sealed interface makes the possible states explicit.

Jetpack Compose can render each state separately.

Benefits

  • Predictable UI behavior
  • Easier debugging
  • Clear error handling
  • Better testability

9. StateFlow in MVVM Architecture

StateFlow is commonly used to expose observable UI state from ViewModel.

Example

class ProductViewModel(
    private val repository: ProductRepository
) : ViewModel() {

    private val _uiState =
        MutableStateFlow<ProductUiState>(
            ProductUiState.Loading
        )

    val uiState: StateFlow<ProductUiState> =
        _uiState.asStateFlow()

    fun loadProducts() {

        viewModelScope.launch {

            try {

                val products = repository.getProducts()

                _uiState.value =
                    ProductUiState.Success(products)

            } catch (exception: CancellationException) {

                throw exception

            } catch (exception: Exception) {

                _uiState.value =
                    ProductUiState.Error(
                        "Unable to load products"
                    )
            }
        }
    }
}

Explanation

The ViewModel requests data from the repository.

It updates StateFlow based on the result.

The UI observes the latest state.

Best Practice

Keep MutableStateFlow private and expose StateFlow publicly.


10. What Is Unidirectional Data Flow?

Unidirectional Data Flow, or UDF, means information moves through the application in a predictable direction.

UDF Diagram

        User Action
             |
             v
       Jetpack Compose
             |
             v
          ViewModel
             |
             v
          Repository
             |
             v
         Data Result
             |
             v
        ViewModel State
             |
             v
       Jetpack Compose

Explanation

The UI sends actions to the ViewModel.

The ViewModel processes those actions.

The ViewModel publishes updated state.

The UI renders that state.

Benefits

  • Predictable state changes
  • Easier debugging
  • Better separation of concerns
  • Reduced unexpected behavior

11. State Hoisting in Jetpack Compose

State hoisting moves state ownership to an appropriate parent component.

Example

@Composable
fun SearchField(
    query: String,
    onQueryChange: (String) -> Unit
) {

    OutlinedTextField(
        value = query,
        onValueChange = onQueryChange,
        label = {
            Text("Search Products")
        }
    )
}

Explanation

SearchField does not own the query state.

It receives the current value and a callback.

Benefits

  • Reusable composables
  • Easier testing
  • Clear state ownership
  • Better integration with ViewModel

Best Practice

Hoist state to the lowest appropriate common owner.

Not every temporary UI detail needs to be stored in ViewModel.


12. MVVM vs MVC vs MVP

Android developers may encounter several architectural patterns.

FeatureMVCMVPMVVM
Main componentsModel, View, ControllerModel, View, PresenterModel, View, ViewModel
UI state managementVariesPresenter-drivenViewModel-driven
Jetpack Compose integrationPossiblePossibleNatural fit
Android Jetpack ViewModelNot requiredNot requiredCommonly used
TestabilityDepends on implementationGenerally goodGenerally good

Which Architecture Should You Choose?

For modern Android applications using Kotlin and Jetpack Compose, MVVM with Unidirectional Data Flow is a practical and widely used choice.

However, architecture quality depends on implementation, not only the pattern name.


Practical Android Mini-Project: Product Catalog Using MVVM

Now let’s build a complete Android mini-project.

Our application will display a list of products using MVVM architecture.

Features

  • Product list
  • Loading indicator
  • Error state
  • Retry functionality
  • Repository abstraction
  • ViewModel
  • StateFlow
  • Jetpack Compose UI
  • Manual refresh

Technology Stack

  • Kotlin
  • Jetpack Compose
  • Material 3
  • ViewModel
  • Kotlin Coroutines
  • StateFlow
  • MVVM

This tutorial uses a local in-memory repository to keep the focus on architecture.


13. Recommended Project Structure

app/
│
└── src/main/java/com/example/mvvmapp/
    │
    ├── data/
    │   └── repository/
    │       ├── ProductRepository.kt
    │       └── ProductRepositoryImpl.kt
    │
    ├── model/
    │   └── Product.kt
    │
    ├── ui/
    │   └── product/
    │       ├── ProductUiState.kt
    │       ├── ProductViewModel.kt
    │       ├── ProductViewModelFactory.kt
    │       └── ProductScreen.kt
    │
    └── MainActivity.kt

Explanation

Each package has a clear responsibility.

The model package contains data models.

The repository package handles data access.

The UI package contains presentation logic and Compose screens.


14. Create the Product Model

Create Product.kt.

data class Product(
    val id: Int,
    val name: String,
    val price: Double,
    val description: String
)

15. Create the Repository Interface

Create ProductRepository.kt.

interface ProductRepository {

    suspend fun getProducts(): List<Product>
}

16. Create the Repository Implementation

Create ProductRepositoryImpl.kt.

class ProductRepositoryImpl : ProductRepository {

    override suspend fun getProducts(): List<Product> {

        delay(800)

        return listOf(
            Product(
                id = 1,
                name = "Android Phone",
                price = 19999.0,
                description = "Powerful Android smartphone"
            ),
            Product(
                id = 2,
                name = "Bluetooth Speaker",
                price = 2499.0,
                description = "Portable wireless speaker"
            ),
            Product(
                id = 3,
                name = "Smart Watch",
                price = 4999.0,
                description = "Health and activity tracking"
            ),
            Product(
                id = 4,
                name = "Wireless Headphones",
                price = 2999.0,
                description = "Comfortable wireless audio"
            )
        )
    }
}

Explanation

The repository simulates a data-loading operation.

The delay represents asynchronous work.

No network or database dependency is required.


17. Create the UI State

Create ProductUiState.kt.

sealed interface ProductUiState {

    data object Loading : ProductUiState

    data class Success(
        val products: List<Product>
    ) : ProductUiState

    data class Error(
        val message: String
    ) : ProductUiState
}

18. Create the ViewModel

Create ProductViewModel.kt.

class ProductViewModel(
    private val repository: ProductRepository
) : ViewModel() {

    private val _uiState =
        MutableStateFlow<ProductUiState>(
            ProductUiState.Loading
        )

    val uiState: StateFlow<ProductUiState> =
        _uiState.asStateFlow()

    private var loadJob: Job? = null

    init {
        loadProducts()
    }

    fun loadProducts() {

        loadJob?.cancel()

        loadJob = viewModelScope.launch {

            _uiState.value = ProductUiState.Loading

            try {

                val products = repository.getProducts()

                _uiState.value =
                    ProductUiState.Success(products)

            } catch (exception: CancellationException) {

                throw exception

            } catch (exception: Exception) {

                _uiState.value =
                    ProductUiState.Error(
                        "Unable to load products. Please try again."
                    )
            }
        }
    }
}

Explanation

The ViewModel coordinates data loading.

It does not know how the repository obtains products.

It exposes a single observable UI state.

The ViewModel also prevents overlapping loads by cancelling the previous job.


19. Create the ViewModel Factory

Create ProductViewModelFactory.kt.

class ProductViewModelFactory(
    private val repository: ProductRepository
) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(
        modelClass: Class<T>
    ): T {

        if (
            modelClass.isAssignableFrom(
                ProductViewModel::class.java
            )
        ) {

            @Suppress("UNCHECKED_CAST")
            return ProductViewModel(repository) as T
        }

        throw IllegalArgumentException(
            "Unknown ViewModel class"
        )
    }
}

Explanation

The factory provides the repository dependency to the ViewModel.

This is a simple example of constructor-based dependency injection.

In larger applications, Hilt can automate dependency creation.


20. Create the Product Screen

Create ProductScreen.kt.

@Composable
fun ProductScreen(
    viewModel: ProductViewModel
) {

    val uiState by viewModel.uiState
        .collectAsStateWithLifecycle()

    ProductContent(
        uiState = uiState,
        onRetry = viewModel::loadProducts
    )
}

Explanation

ProductScreen acts as a route-level composable.

It connects the ViewModel to the UI.

The actual UI rendering is delegated to ProductContent.

This makes the content composable easier to preview and test.


21. Create the Stateless UI Content

@Composable
fun ProductContent(
    uiState: ProductUiState,
    onRetry: () -> Unit
) {

    Scaffold(
        topBar = {

            TopAppBar(
                title = {
                    Text("MVVM Product Catalog")
                }
            )
        }
    ) { paddingValues ->

        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {

            when (uiState) {

                ProductUiState.Loading -> {

                    CircularProgressIndicator(
                        modifier = Modifier.align(
                            Alignment.Center
                        )
                    )
                }

                is ProductUiState.Success -> {

                    Column {

                        Button(
                            onClick = onRetry,
                            modifier = Modifier.padding(16.dp)
                        ) {

                            Text("Refresh Products")
                        }

                        LazyColumn(
                            contentPadding = PaddingValues(16.dp),
                            verticalArrangement =
                                Arrangement.spacedBy(12.dp)
                        ) {

                            items(
                                items = uiState.products,
                                key = { it.id }
                            ) { product ->

                                ProductCard(product)
                            }
                        }
                    }
                }

                is ProductUiState.Error -> {

                    Column(
                        modifier = Modifier.align(
                            Alignment.Center
                        ),
                        horizontalAlignment =
                            Alignment.CenterHorizontally,
                        verticalArrangement =
                            Arrangement.spacedBy(16.dp)
                    ) {

                        Text(
                            text = uiState.message,
                            color = MaterialTheme.colorScheme.error
                        )

                        Button(
                            onClick = onRetry
                        ) {

                            Text("Retry")
                        }
                    }
                }
            }
        }
    }
}

Explanation

ProductContent receives immutable UI state and a callback.

It does not depend directly on ViewModel.

This follows the principles of state hoisting and separation of concerns.


22. Create the Product Card

@Composable
fun ProductCard(
    product: Product
) {

    Card(
        modifier = Modifier.fillMaxWidth()
    ) {

        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement =
                Arrangement.spacedBy(8.dp)
        ) {

            Text(
                text = product.name,
                style = MaterialTheme.typography.titleMedium
            )

            Text(
                text = product.description,
                style = MaterialTheme.typography.bodyMedium
            )

            Text(
                text = "₹${product.price}",
                style = MaterialTheme.typography.titleSmall,
                color = MaterialTheme.colorScheme.primary
            )
        }
    }
}

Explanation

ProductCard only renders product information.

It can be reused in other screens without depending on ViewModel or repository classes.


23. Create MainActivity

class MainActivity : ComponentActivity() {

    override fun onCreate(
        savedInstanceState: Bundle?
    ) {

        super.onCreate(savedInstanceState)

        setContent {

            MaterialTheme {

                val viewModel: ProductViewModel =
                    viewModel(
                        factory = ProductViewModelFactory(
                            ProductRepositoryImpl()
                        )
                    )

                ProductScreen(
                    viewModel = viewModel
                )
            }
        }
    }
}

Explanation

MainActivity sets the Compose content.

The ViewModel is obtained using a factory.

The repository is provided through constructor injection.

For a larger application, dependency creation should be moved into an application-level dependency injection setup.


24. Required Dependencies

Add the following dependencies to your app module if they are not already included.

dependencies {

    implementation(
        "androidx.lifecycle:lifecycle-viewmodel-ktx:<version>"
    )

    implementation(
        "androidx.lifecycle:lifecycle-viewmodel-compose:<version>"
    )

    implementation(
        "androidx.lifecycle:lifecycle-runtime-compose:<version>"
    )

    implementation(
        "org.jetbrains.kotlinx:kotlinx-coroutines-android:<version>"
    )

    implementation(
        "androidx.compose.material3:material3"
    )
}

Replace version placeholders with compatible stable versions.

If your project uses the Compose BOM, keep Compose library versions managed through that BOM.

Important

Material 3 TopAppBar APIs may require opting into ExperimentalMaterial3Api depending on the library version.

Use the annotation where required:

@OptIn(ExperimentalMaterial3Api::class)

25. Expected UI — Loading

+--------------------------------+
|       MVVM Product Catalog     |
|                                |
|                                |
|              ○                 |
|                                |
|        Loading products...     |
|                                |
+--------------------------------+

26. Expected UI — Success

+--------------------------------+
|       MVVM Product Catalog     |
|                                |
|      [ Refresh Products ]      |
|                                |
| +----------------------------+ |
| | Android Phone              | |
| | Powerful Android smartphone| |
| | ₹19999.0                   | |
| +----------------------------+ |
|                                |
| +----------------------------+ |
| | Bluetooth Speaker          | |
| | Portable wireless speaker  | |
| | ₹2499.0                    | |
| +----------------------------+ |
|                                |
| +----------------------------+ |
| | Smart Watch                | |
| | Health and activity        | |
| | tracking                   | |
| | ₹4999.0                    | |
| +----------------------------+ |
|                                |
+--------------------------------+

27. Expected UI — Error

+--------------------------------+
|       MVVM Product Catalog     |
|                                |
|                                |
|  Unable to load products.      |
|       Please try again.        |
|                                |
|            [ Retry ]           |
|                                |
+--------------------------------+

28. How the Complete MVVM Application Works

Step 1: MainActivity Starts

MainActivity creates the Compose UI and obtains the ViewModel.

Step 2: ViewModel Initializes

The ViewModel begins loading products.

Step 3: StateFlow Publishes Loading

The UI displays a progress indicator.

Step 4: Repository Loads Data

The repository returns the product list.

Step 5: ViewModel Publishes Success

StateFlow receives ProductUiState.Success.

Step 6: Compose Recomposition

The UI observes the new state and displays the products.

Step 7: User Refreshes

The UI calls the ViewModel’s loadProducts() function.

Step 8: ViewModel Reloads Data

The loading process begins again.

This demonstrates a complete unidirectional data flow.


29. How to Test MVVM Architecture

MVVM improves testability because the ViewModel can be tested without launching the full Android UI.

Fake Repository

class FakeProductRepository : ProductRepository {

    override suspend fun getProducts(): List<Product> {

        return listOf(
            Product(
                id = 1,
                name = "Test Product",
                price = 100.0,
                description = "Testing MVVM"
            )
        )
    }
}

ViewModel Test

The following test uses the MainDispatcherRule introduced in our previous Kotlin Flow testing tutorial.

@OptIn(ExperimentalCoroutinesApi::class)
class ProductViewModelTest {

    @get:Rule
    val mainDispatcherRule = MainDispatcherRule()

    @Test
    fun `products load successfully`() = runTest {

        val repository = FakeProductRepository()

        val viewModel = ProductViewModel(repository)

        advanceUntilIdle()

        val state = viewModel.uiState.value

        assertTrue(
            state is ProductUiState.Success
        )
    }
}

Explanation

The test uses a fake repository.

No real network request is required.

The test verifies the ViewModel’s final UI state.


30. MVVM Architecture with Dependency Injection

Dependency injection allows dependencies to be provided from outside a class.

Without Dependency Injection

class ProductViewModel : ViewModel() {

    private val repository =
        ProductRepositoryImpl()
}

With Constructor Injection

class ProductViewModel(
    private val repository: ProductRepository
) : ViewModel()

Benefits

  • Reduced coupling
  • Easier testing
  • Flexible implementations
  • Better scalability

Production Recommendation

Use Hilt when dependency management becomes complex.

However, understanding manual dependency injection first is valuable.


31. MVVM Architecture Best Practices

Follow these recommendations:

  • Keep composables focused on UI rendering.
  • Store screen state in ViewModel when appropriate.
  • Expose immutable StateFlow.
  • Use repositories for data access.
  • Prefer constructor injection.
  • Use Unidirectional Data Flow.
  • Keep UI state models explicit.
  • Use lifecycle-aware Flow collection.
  • Avoid Android Context references in ordinary ViewModels.
  • Keep domain and data responsibilities separate.
  • Handle coroutine cancellation correctly.
  • Avoid performing API calls directly inside composables.
  • Write ViewModel unit tests.
  • Avoid unnecessary abstraction layers.
  • Organize packages by feature as applications grow.

32. Common MVVM Architecture Mistakes

Mistake 1: Putting Business Logic Inside Composables

Composables should focus on rendering UI and forwarding interactions.

Mistake 2: Creating Repositories Directly Inside ViewModel

Prefer constructor injection.

Mistake 3: Exposing MutableStateFlow Publicly

Expose read-only StateFlow.

Mistake 4: Using ViewModel for Every Small UI State

Temporary UI details can remain inside composables when appropriate.

Mistake 5: Making ViewModels Too Large

Split responsibilities into repositories and use cases when complexity grows.

Mistake 6: Mixing Data Access with UI Rendering

Keep database and network operations outside composables.

Mistake 7: Ignoring Cancellation

Preserve CancellationException.

Mistake 8: Creating Too Many Layers

Do not introduce unnecessary abstractions into simple applications.

Mistake 9: Using Unmanaged CoroutineScopes

Prefer lifecycle-aware coroutine ownership.

Mistake 10: Skipping Unit Tests

Test ViewModel behavior with fake repositories.


33. MVVM Architecture Quick Reference

ComponentResponsibility
ModelApplication data
ViewUI rendering
ViewModelUI state and presentation logic
RepositoryData access abstraction
StateFlowObservable UI state
MutableStateFlowMutable state holder
viewModelScopeViewModel-owned coroutines
collectAsStateWithLifecycle()Lifecycle-aware state collection
UDFPredictable data and action flow
Dependency InjectionExternal dependency provisioning
HiltAndroid dependency injection framework
SavedStateHandleSaved state support in ViewModel

34. Practical Exercises

Exercise 1: Simple MVVM

Create a counter application using ViewModel and StateFlow.

Exercise 2: Repository Pattern

Create a repository interface that returns a list of users.

Exercise 3: UI State

Implement Loading, Success, and Error states.

Exercise 4: State Hoisting

Create a reusable TextField composable with value and onValueChange parameters.

Exercise 5: Manual Dependency Injection

Create a ViewModel factory.

Exercise 6: Product Catalog

Build the complete product catalog mini-project.

Exercise 7: Search Feature

Add product search functionality.

Exercise 8: Error Handling

Simulate repository failures and display an error screen.

Exercise 9: Unit Testing

Test the ViewModel using a fake repository.

Exercise 10: Architecture Improvement

Separate the project into data, domain, and UI packages.


35. Frequently Asked Questions

What is MVVM architecture in Android?

MVVM stands for Model-View-ViewModel. It separates application data, UI rendering, and presentation logic.

Why is MVVM used in Android?

MVVM improves maintainability, testability, separation of concerns, and state management.

Is MVVM suitable for Jetpack Compose?

Yes. MVVM works naturally with Jetpack Compose and StateFlow.

What is the role of ViewModel?

ViewModel manages UI-related state and coordinates operations required by the screen.

What is the Repository Pattern?

The Repository Pattern provides an abstraction for accessing application data.

What is Unidirectional Data Flow?

UDF is an approach where UI actions and state updates move through predictable paths.

Should every Android application use MVVM?

Not necessarily. Architecture should match application complexity and requirements.

However, MVVM is a practical choice for many modern Android applications.

What is the difference between ViewModel and Repository?

ViewModel manages presentation state.

Repository provides data access.

Is Hilt required for MVVM?

No. MVVM can use manual dependency injection or other dependency injection frameworks.

Can MVVM be unit tested?

Yes. ViewModels can be tested using fake repositories and coroutine testing utilities.


What We’ve Learned

In this tutorial, we explored:

  • Android application architecture
  • MVVM fundamentals
  • Model responsibilities
  • View responsibilities
  • ViewModel responsibilities
  • Repository Pattern
  • UI state management
  • StateFlow integration
  • Unidirectional Data Flow
  • State hoisting
  • Dependency injection concepts
  • Jetpack Compose integration
  • Practical product catalog application
  • ViewModel unit testing
  • Common mistakes and best practices

MVVM is a powerful architectural pattern for building maintainable Android applications.

By combining Kotlin, Jetpack Compose, ViewModel, StateFlow, and repositories, developers can create applications with clear responsibilities and predictable state management.

These concepts form the foundation for more advanced Android architecture patterns, including Clean Architecture, domain layers, use cases, and multi-module applications.


What’s Next?

In our next tutorial, we’ll explore:

Article 39 — Clean Architecture in Android with Kotlin & Jetpack Compose: Data, Domain & Presentation Layers

You’ll learn:

  • What Clean Architecture is
  • Why Clean Architecture matters
  • Data layer
  • Domain layer
  • Presentation layer
  • Dependency Rule
  • Repository interfaces
  • Use cases
  • Dependency injection
  • StateFlow integration
  • Jetpack Compose UI
  • Practical Clean Architecture mini-project
  • Common mistakes
  • Production best practices

Happy Coding!

Continue learning modern Android development with Moiks Developer Blog.

Explore Apps by Moiks Studio

Discover our Android apps and games on Google Play.

View All Android Apps →

Leave a Comment