Back-end14-minute read

MVVM Architecture: A Definitive Guide for Android

The MVVM pattern didn’t originate with Android, but modern Android readily supports it. This guide explores MVVM’s pros and cons, and when Clean Architecture justifies the additional code it requires.

Last updated: Dec 3, 2026

Toptalauthors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.

The MVVM pattern didn’t originate with Android, but modern Android readily supports it. This guide explores MVVM’s pros and cons, and when Clean Architecture justifies the additional code it requires.

Last updated: Dec 3, 2026

Toptalauthors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.
Bishoy Gendy
10 Years of Experience

Bishoy is a senior software engineer who specializes in mobile development. Throughout his decade-long career, he has scaled high-traffic Android products and features for startups as well as global enterprise businesses, including Meta and Google. Bishoy holds a bachelor’s degree in computer engineering from Alexandria University.

Previous Role

Senior Software Engineer

Previously At

MetaGoogle
Share

User interface (UI) code is easy to overload. A screen designed solely for presenting information can end up carrying application state, business rules, or data-access code as well, which means routine features consequently take longer to build and test.

Model-View-ViewModel (MVVM) architecture offers Android developers one way to separate a UI from the state and business logic that support it. While MVVM seems straightforward in theory, my experience building and refactoring mobile applications has taught me that its boundaries are less obvious in practice.

This guide explains how to divide responsibilities within an Android application through a practical Kotlin example. It also explores Clean Architecture, which extends MVVM’s separation of concerns to business rules and data access, and when the added structure improves the design enough to justify its complexity.

What Is MVVM Architecture?

MVVM architecture is a pattern that separates the View the user sees, the ViewModel managing presentation state and logic, and the Model providing application data and business logic. The result is a state-driven interface in which the View renders what the ViewModel exposes. That way, the View doesn’t need to manage data access or business rules itself.

Components of MVVM Architecture

MVVM applies the separation of concerns principle, assigning each component a distinct responsibility:

  • The View renders UI state and captures user interactions, but it contains no business logic and doesn’t retrieve data from the Model.
  • The ViewModel manages presentation logic and prepares state for the View to render. It doesn’t hold references to the specific View implementation or other UI objects that Android may recreate.
  • The Model represents application data and the operations or business rules associated with it. In a modern Android application, this responsibility may span repositories, domain objects, databases, and remote services rather than one literal Model class.

The Origin of the MVVM Pattern

The name MVVM builds on the naming convention established by earlier patterns such as Model-View-Controller (MVC) and Model-View-Presenter (MVP). Its direct precursor was Martin Fowler’s Presentation Model from 2004, which moved presentation state and behavior out of the interface and into a separate object.

MVVM later became closely associated with Windows Presentation Foundation (WPF), whose data-binding capabilities allowed Views to stay synchronized with presentation state. The pattern later spread to other ecosystems, including Android. The release of Jetpack Compose 1.0 in 2021 reinforced MVVM’s position by making declarative, state-driven UI a core part of Android’s toolkit for modern application development.

How the MVVM Architecture Pattern Works

MVVM defines two directions of communication: User events pass from the View to the ViewModel, and the UI state returns from the ViewModel to the View.

MVVM Architecture Flow

A typical flow has three steps:

  1. The View sends an event. A user interacts in some way: They select, submit, save, or maybe delete content. The View reports that action to the ViewModel rather than deciding how it should be processed.
  2. The ViewModel coordinates the operation. It asks the Model to retrieve or modify data, then updates its state based on the result.
  3. The View renders the resulting state. The ViewModel exposes state (e.g., a loading flag or progress value, data received, or error details) and the View reacts to it by rendering the UI accordingly.

The Model doesn’t need to know which View is displaying its data. The View observes the state and responds when it changes, which is an application of the Observer pattern. Keeping data operations independent from rendering also makes ViewModel logic easier to test.

MVVM architecture diagram showing the View sending events to the ViewModel and Model, and state returning to the View.

Data Binding in MVVM

Data binding connects state exposed by the ViewModel to the View. When the state changes, the View renders the new value without needing to be updated manually.

There are two common forms:

  • One-way binding: State flows from the ViewModel to the View.
  • Two-way binding: A user-editable value can also be changed by the View and synced back into the ViewModel.

Android developers can connect ViewModel state to the interface in different ways. Traditional Android interfaces defined in XML can use the Data Binding Library to link observable data to UI properties. In Jetpack Compose, UI elements read state and Compose redraws the affected elements when the state changes, a process called recomposition. The underlying principle is the same: UI is a function of state.

Data binding works best when kept simple. The more implicit or indirect the flow, the harder it is to trace the source of a UI change; at an extreme it can even impact responsiveness.

Commands and Behaviors

Some MVVM frameworks use commands and behaviors to keep interaction logic out of the View. A command represents user actions like deleting a record or submitting a form; a behavior is reusable interaction logic, like formatting or validation triggers, that gets attached to a UI element.

Kotlin and Compose don’t require either concept to be represented as a separate object. User actions are commonly passed through callbacks, and reusable interaction logic can be defined once and applied to multiple UI elements. The following Kotlin example creates a Compose button that invokes a ViewModel method when the user clicks “Save”:

Button(
    onClick = { viewModel.savePost() }
) {
    Text("Save")
}

The code inside onClick is a callback that runs when the button is clicked. It calls the ViewModel’s savePost() method, which performs the role a command would serve in other MVVM frameworks. The View reports what the user did; the ViewModel decides how to process it.

View-first and ViewModel-first Composition

View-first and ViewModel-first composition describe which component is created first. In View-first composition, the application opens a View and then provides its ViewModel. In ViewModel-first composition, the application creates the ViewModel first and then selects the View that will display its state.

While ViewModel-first composition can give the ViewModel more control over application flow, the application then needs a way to select the correct View and decide how long the ViewModel should remain available. In Android, View-first composition is the more natural fit because the application usually opens a screen and then provides the ViewModel responsible for its state. The ViewModel can remain available across related screens when information needs to be retained or shared.

Advantages and Criticisms of MVVM Architecture

As with any architecture, MVVM isn’t automatically the right choice for every application. It’s most useful when complex UIs involve enough state and interaction to justify separating them from rendering. Here’s an overview of its key benefits and limitations.

Advantages of MVVM

MVVM introduces additional structure, so its value depends on whether that structure makes the code easier to develop and maintain. When implemented well, the main benefits developers can expect include:

  • Better testability: Logic kept in ViewModels can generally be tested without rendering the UI or depending on a particular screen.
  • Clearer UI state: Loading and error conditions are easier to follow when represented as state instead of scattered UI updates.
  • Reusable presentation logic: ViewModel logic can support multiple compatible Views when the underlying behavior is shared.
  • Reduced coupling: Changes to data sources or UI requirements have less of a ripple effect throughout the codebase.

MVVM Value: A Real-world MVVM Architecture Example

I saw these benefits firsthand on a project where a pair of Android applications initially built with MVP had grown to more than 400 screens total. End-to-end testing exposed serious life cycle and navigation problems, particularly when users moved through long sequences of screens. Moving the relevant logic to MVVM took about a month and did not add functionality, but substantially improved stability and reduced codebase size. Crashes fell to almost zero, bringing the Android applications much closer to their iOS counterparts in stability.

Criticisms and Limitations of MVVM

I’ve seen too many developers adopt MVVM and other approaches without due consideration. For small applications, separating responsibilities via extra layers may not be worth the additional setup code and maintenance. And MVVM can have pitfalls, even when it is the right choice:

  • Bloated ViewModels: A complex screen can accumulate unrelated responsibilities until its ViewModel becomes unwieldy and unmaintainable. ViewModels are better scoped to problems than screens.
  • Impossible state: A state with isLoading, hasError, and hasData, for example, can describe conflicting conditions, leaving the UI to decide which one takes precedence. A more coherent state design can reduce or eliminate ill-defined behavior.
  • Conflation of business and presentation logic: As applications scale, it’s easy for a ViewModel to become a jumble of business rules, data coordination, and UI state, which is the opposite of MVVM’s intention. Keeping domain logic and UI logic in their proper layers takes discipline.

MVVM vs. MVC, MVP, and Presentation Model: Key Differences

MVVM is one of several popular architectures used to separate application logic from UI concerns. The main differences lie in how each architectural pattern handles user input and communicates changes back to the View. Here’s how they compare:

MVVM vs. MVC

In MVC, the Controller responds to user actions and coordinates the View and Model. Depending on the implementation, the Controller or View may also take on data-handling responsibilities, and the View may request data directly from the Model.

MVVM, on the other hand, gives the View a ViewModel that exposes presentation state, and the View never queries the Model directly. This works naturally with declarative, state-driven UIs. MVVM’s separation of UI state from the Activity is especially important in Android, where an Activity commonly represents a screen. Without clear boundaries, the Activity can accumulate data-fetching and life cycle responsibilities and quickly become bloated. Android’s ViewModel class exists specifically to hold UI-related data and logic across Activity recreation, such as after a screen rotation, without retaining the old Activity.

MVC may be useful as a simple introductory pattern, but it’s not a strong default for a growing Android application.

MVVM vs. MVP

MVP uses a Presenter that typically communicates with the View through an explicit interface, telling it how to update itself by calling methods like showLoading() or showError(). The View interface can add repetitive code because each UI update must be declared in the interface and implemented in the View. MVVM instead exposes presentation state for the View to observe and react to. A life cycle-aware Android ViewModel can retain UI-related state across configuration changes without holding a reference to the View itself.

MVVM vs. Presentation Model

It’s harder to draw strict lines between MVVM and Presentation Model; they’re very similar. Both patterns fundamentally emphasize the separation of presentation state from the rendered UI. MVVM has a stronger association with declarative binding, partly because WPF used it prominently, but neither pattern requires a particular binding mechanism.

Below is a summary of the main differences between the four patterns:

Pattern Main Intermediary Typical Communication
MVCControllerController handles input and coordinates the View and Model
MVPPresenterPresenter calls methods defined by a View interface
MVVMViewModelView sends events and observes ViewModel state
Presentation ModelPresentation ModelView reads or binds to presentation state

MVVM Architecture in Modern Android Development

Android provides components that respond automatically when a screen is created, stopped, or recreated, reducing the amount of life cycle code developers need to write. Jetpack, a collection of Android libraries, and the wider Kotlin ecosystem provide several tools compatible with MVVM. Developers can combine them according to how an application manages state and connects its components.

Modern Android Frameworks and Libraries for MVVM

Android does not provide a single framework that implements MVVM end-to-end. Developers use a combination of Jetpack and Kotlin tools for tasks such as storing UI state and delivering data to the screen. Common tools and libraries used in Android MVVM implementations are described below:

  • StateFlow is an observable state holder integrated with Kotlin’s coroutine-based Flow APIs. It exposes a current value and subsequent updates, making it well suited to UI state.
  • Jetpack Compose renders UI from state and updates the affected parts of the interface when that state changes. collectAsStateWithLifecycle() is the recommended Android-specific way to collect a Flow into Compose state while respecting the life cycle.
  • Kotlin coroutines and viewModelScope run asynchronous work within a ViewModel’s lifetime; work in viewModelScope is canceled when the ViewModel is cleared.
  • LiveData remains supported, particularly in existing applications built with Android Views, although Kotlin Flow APIs integrate more directly with modern Kotlin-based architectures.
  • Networking libraries retrieve remote data, and Room stores data locally on the device.
  • Hilt provides dependency injection for Android, commonly constructing repository and use case dependencies before supplying them to a ViewModel.
  • Navigation libraries manage movement between screens and determine how long ViewModel instances remain available or whether screens share them.

These technologies support MVVM architecture, reducing implementation effort, but it’s still up to the development team to determine how responsibilities are divided between the View, ViewModel, and Model.

A Simple Android MVVM Architecture Example

The following Kotlin example demonstrates the basic MVVM relationship. A Post holds the data for each post, PostsRepository retrieves the data, PostsViewModel prepares the UI state, and the Compose View PostsScreen displays it.

data class Post(
    val id: Int,
    val title: String
)

interface PostsRepository {
    suspend fun getPosts(): List<Post>
}

sealed interface PostsUiState {
    data object Loading : PostsUiState

    data class Content(
        val posts: List<Post>
    ) : PostsUiState

    data object Empty : PostsUiState

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

class PostsViewModel(
    private val repository: PostsRepository
) : ViewModel() {

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

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

    init {
        loadPosts()
    }

    fun loadPosts() {
        viewModelScope.launch {
            _uiState.value = PostsUiState.Loading

            runCatching { repository.getPosts() }
                .onSuccess { posts ->
                    _uiState.value =
                        if (posts.isEmpty()) {
                            PostsUiState.Empty
                        } else {
                            PostsUiState.Content(posts)
                        }
                }
                .onFailure { error ->
                    _uiState.value =
                        PostsUiState.Error(
                            error.message ?: "Unable to load posts"
                        )
                }
        }
    }
}

The Compose code below defines PostsScreen, which reads the current state and displays the corresponding interface:

@Composable
fun PostsScreen(viewModel: PostsViewModel) {
    when (
        val state =
            viewModel.uiState.collectAsStateWithLifecycle().value
    ) {
        PostsUiState.Loading ->
            CircularProgressIndicator()

        PostsUiState.Empty ->
            Text("No posts")

        is PostsUiState.Content ->
            PostList(state.posts)

        is PostsUiState.Error ->
            Text(state.message)
    }
}

A real application may still need to display existing posts while refreshing them in the background, so content and loading can sometimes occur together.

The example deliberately has no use case or multi-module structure to keep the core MVVM relationship clear: The View sends user actions to the ViewModel, the ViewModel exposes a coherent UI state, and the data layer supplies the underlying information.

Combining MVVM With Clean Architecture in Android

MVVM separates the interface from presentation logic, but it doesn’t prescribe how an application should organize business rules or data access. Clean Architecture places those responsibilities in separate layers when the codebases behind complex projects need clearer divisions.

How MVVM Fits Into Clean Architecture

Clean Architecture doesn’t replace MVVM but it incorporates View and ViewModel as the presentation layer of a broader application structure. The core MVVM flow remains the same: A Compose screen sends user events to the ViewModel, which calls a repository or a use case and converts the result into UI state. Kotlin Flow or StateFlow can then deliver the state for Compose to render.

The domain and data layers divide the responsibilities associated with the Model. The domain layer contains business rules and use cases, while the data layer handles access to databases and network services. The domain layer doesn’t depend on the interface or specific data-source implementations, allowing business rules to remain unchanged when the interface or data sources change.

Smaller applications may allow ViewModels to communicate directly with repositories, whereas large, data-heavy applications often benefit from a separate domain layer. Practically speaking, you should only add a layer to solve a problem, not to artificially complete an architecture diagram.

Benefits and Limitations of Clean Architecture

Clean Architecture can make a complex Android application easier to maintain, but its additional structure also brings trade-offs. Here’s an overview of the main benefits and limitations:

Benefits
Limitations
Keeps complex business rules out of ViewModels

Isolates reusable use cases so they can support multiple ViewModels or features

Uses repository abstractions to make data sources easier to replace and test

Gives large development teams clearer boundaries between areas of ownership
Adds interfaces, classes, and mapping code

Spreads an operation across more files, making its flow harder to trace

Adds little value when a ViewModel can communicate cleanly with a repository

Introduces overhead that might outweigh the benefits for small-scale projects when implemented across multiple modules

Building MVVM With Clean Architecture in Android

The following example extends the posts implementation with domain and data layers. PostsScreen and PostsUiState stay unchanged, while PostsViewModel receives a use case instead of accessing the repository directly. Hilt assembles the required dependencies.

Building the Domain Layer

The domain layer contains operations that should remain independent of the interface. In the posts example, GetPostsUseCase asks the repository to refresh its data and then exposes the stored posts as a Flow:

class GetPostsUseCase(
    private val repository: PostsRepository
) {
    operator fun invoke(): Flow<List<Post>> =
        repository.observePosts()
            .onStart { repository.refreshPosts() }
}

The use case depends on the PostsRepository abstraction and does not know whether the posts come from a database or network service. A smaller application could call the repository directly; the use case becomes valuable when the operation is reused or gains additional business rules.

Building the Data Layer

The domain layer defines the data operations it needs through PostsRepository. The data layer implements the contract and hides whether posts come from local storage or a remote service:

interface PostsRepository {
    fun observePosts(): Flow<List<Post>>
    suspend fun refreshPosts()
}

class PostsRepositoryImpl(
    private val local: PostsLocalDataSource,
    private val remote: PostsRemoteDataSource
) : PostsRepository {

    override fun observePosts(): Flow<List<Post>> =
        local.observePosts()

    override suspend fun refreshPosts() {
        val posts = remote.fetchPosts()
        local.replacePosts(posts)
    }
}

Here, the local data source acts as the source of truth for reads. The repository observes local data and refreshes it from the network when needed. Flow exposes those changes through the repository contract without coupling higher layers to the database or remote service that produced them.

Because higher layers depend on the repository contract, the database or remote service can change without requiring corresponding changes in the domain or presentation layers.

Connecting the Layers With Hilt

Hilt constructs the dependency chain linking the ViewModel, use case, and repository implementation. Begin by adding @Inject to the constructors of PostsRepositoryImpl and GetPostsUseCase:

class PostsRepositoryImpl @Inject constructor(
    private val local: PostsLocalDataSource,
    private val remote: PostsRemoteDataSource
) : PostsRepository {
    // Existing implementation
}

class GetPostsUseCase @Inject constructor(
    private val repository: PostsRepository
) {
    // Existing implementation
}

A Hilt module then binds the repository interface to its implementation:

@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {

    @Binds
    @Singleton
    abstract fun bindPostsRepository(
        implementation: PostsRepositoryImpl
    ): PostsRepository
}

The abbreviated PostsViewModel below receives GetPostsUseCase from Hilt and converts its Flow into the same PostsUiState used by the simple example:

@HiltViewModel
class PostsViewModel @Inject constructor(
    private val getPosts: GetPostsUseCase
) : ViewModel() {

    val uiState: StateFlow<PostsUiState> =
        getPosts()
            .map<List<Post>, PostsUiState> { posts ->
                if (posts.isEmpty()) {
                    PostsUiState.Empty
                } else {
                    PostsUiState.Content(posts)
                }
            }
            .catch { error ->
                emit(
                    PostsUiState.Error(
                        error.message ?: "Unable to load posts"
                    )
                )
            }
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = PostsUiState.Loading
            )
}

The local and remote data sources must also be available to Hilt through injectable constructors or @Provides methods. The @Singleton annotation keeps one repository instance for the application’s lifetime. Hilt manages object construction and scope, but the developer still decides which layers and abstractions the application needs.

Matching Architecture to Application Complexity

MVVM gives Android applications a practical way to separate UI rendering from the state and data operations behind it. ViewModel preserves state across interface recreation, and StateFlow and Compose carry updates back to the screen. Like any pattern, MVVM is best used when it’s a clear solution to a concrete problem; adding a use case or interface without a specific need often makes the code harder to follow without improving the design.

More structure is not automatically better. In larger applications, Clean Architecture can extend MVVM by moving complex business rules out of ViewModels and giving teams clearer ownership of the codebase, but its benefits must justify the extra code and indirection.

Don’t treat the most elaborate version of MVVM architecture as the ideal. Architecture should make the system easier to understand and maintain; if a layer does neither, leave it out.

Understanding the basics

  • MVVM (Model-View-ViewModel) is an architectural pattern that separates an application into three parts: The View renders the interface, the ViewModel prepares and manages UI state, and the Model handles application data and related operations.

  • MVVM stands for Model-View-ViewModel, referring to the three components used to separate interface rendering, presentation state, and application data.

  • MVVM keeps UI rendering separate from state management and data operations. Developers use it to make interface code easier to test, change, and maintain, particularly in applications with complex UI state.

  • MVVM and Clean Architecture address different parts of application design. MVVM defines how the UI interacts with presentation state and data, whereas Clean Architecture separates the wider codebase into layers to keep business rules independent of the UI and data sources. They are often used together.

  • MVVM is not always better than MVP. It suits state-driven interfaces because a ViewModel exposes observable state for the View to render. In MVP, a Presenter usually tells the View what to display through direct method calls.

  • No. MVVM remains widely used in Android development and works well with tools such as ViewModel, StateFlow, and Jetpack Compose. However, it is one of several valid architectural approaches, not a universal requirement.

Hire a Toptal expert on this topic.
Hire Now
Bishoy Gendy

Bishoy Gendy

10 Years of Experience

London, United Kingdom

Member since December 14, 2021

About the author

Bishoy is a senior software engineer who specializes in mobile development. Throughout his decade-long career, he has scaled high-traffic Android products and features for startups as well as global enterprise businesses, including Meta and Google. Bishoy holds a bachelor’s degree in computer engineering from Alexandria University.

authors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.
Previous Role
Senior Software Engineer
PREVIOUSLY AT
MetaGoogle

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

Join the Toptal® community.