How to Implement Android MVVM Clean Architecture for a Scalable App

Share
An Android developer is coding on a laptop using a code editor in a workspace.

MVVM (Model-View-ViewModel) combined with clean architecture offers a clear way to build Android apps that are maintainable, scalable, and easier to test. MVVM separates the UI from business logic by organizing code into View, ViewModel, and Model components. Clean architecture adds structure by dividing your app into layers, Presentation, Domain, and Data, with strict rules about dependencies flowing inward. This guide explains how to organize your project, set up each layer, connect them, and keep your code testable and modular.

What is MVVM and clean architecture in Android development?

MVVM stands for Model-View-ViewModel. It divides your app into three parts: the View handles UI and user input, the ViewModel manages UI data and logic, and the Model represents data and business rules. This separation makes your UI code cleaner and easier to test.

Clean architecture organizes your app into layers with clear roles and strict dependency rules. The common layers are:

  • Presentation: UI components and ViewModels
  • Domain: business logic and UseCases
  • Data: repositories and data sources

Each inner layer is independent of the outer ones, so your core business logic stays stable even if UI or data details change.

MVVM fits well with clean architecture: the ViewModel lives in the Presentation layer and interacts with UseCases in the Domain layer. UseCases then communicate with Repositories in the Data layer to get or save data. This setup keeps responsibilities clear and dependencies unidirectional, improving flexibility and maintainability.

How do I organize my Android project following clean architecture?

Organize your project by separating it into three main packages or modules matching the layers:

  • presentation: Activities, Fragments, ViewModels, and UI logic
  • domain: business rules, UseCases, and domain models
  • data: data sources (network, database), Repositories, and data models

For small to medium apps, organizing these as packages inside one module works well. For larger apps, using separate Gradle modules enforces boundaries more strictly and improves build times.

Within each package, group classes by feature or functionality to keep related code together. For example, inside the data package, use subpackages for remote, local, and repository implementations.

Keep dependencies going inward only: outer layers can depend on inner ones, but the domain layer should not depend on Android framework classes or outer layers. This separation keeps your business logic testable and independent of UI or data details.

An Android developer is organizing project folders related to an Android app on a laptop.

How to set up the ViewModel, UseCase, Repository, and Data Source layers?

  1. Create the UseCase in the domain layer. This class represents one business action and doesn't know about UI or data source details.
class FetchUserUseCase(private val userRepository: UserRepository) {
    suspend operator fun invoke(userId: String): User {
        return userRepository.getUser(userId)
    }
}
  1. Define the Repository interface in the domain layer. It abstracts data operations.
interface UserRepository {
    suspend fun getUser(userId: String): User
}
  1. Implement the Repository in the data layer. This class fetches data from one or more sources (network, database).
class UserRepositoryImpl(
    private val remoteDataSource: UserRemoteDataSource,
    private val localDataSource: UserLocalDataSource
) : UserRepository {
    override suspend fun getUser(userId: String): User {
        val cachedUser = localDataSource.getUser(userId)
        return cachedUser ?: remoteDataSource.fetchUser(userId).also {
            localDataSource.saveUser(it)
        }
    }
}
  1. Set up Data Sources. Keep them focused on specific data providers like network or database.
interface UserRemoteDataSource {
    suspend fun fetchUser(userId: String): User
}

interface UserLocalDataSource {
    suspend fun getUser(userId: String): User?
    suspend fun saveUser(user: User)
}
  1. Create the ViewModel in the presentation layer. It calls the UseCase and exposes UI state.
class UserViewModel(private val fetchUserUseCase: FetchUserUseCase) : ViewModel() {
    private val _user = MutableLiveData<User>()
    val user: LiveData<User> = _user

    fun loadUser(userId: String) {
        viewModelScope.launch {
            val result = fetchUserUseCase(userId)
            _user.value = result
        }
    }
}

Each layer has a distinct role: the ViewModel manages UI data and lifecycle, the UseCase encapsulates business logic, the Repository handles data retrieval logic, and Data Sources interact with actual data providers.

How to wire dependencies and manage data flow across layers?

Use dependency injection (DI) to provide each layer with the implementations it needs without hardcoding them. This makes testing and maintenance easier.

  1. Set up DI with a framework like Hilt or Dagger. Provide Repository implementations to the domain layer and UseCases to the ViewModel.
  2. Inject dependencies into your ViewModel. Example using Hilt:
@HiltViewModel
class UserViewModel @Inject constructor(
    private val fetchUserUseCase: FetchUserUseCase
) : ViewModel() { ... }
  1. Use reactive streams such as LiveData or Kotlin Flow in your ViewModel to observe data changes from UseCases. This keeps the UI in sync automatically.
  2. Follow this data flow:
  • View observes LiveData from ViewModel
  • ViewModel calls UseCase
  • UseCase calls Repository
  • Repository queries Data Sources

Because each layer only knows the layer below it, your app avoids tight coupling and is easier to extend or modify. For example, switching from one caching strategy to another only requires changes in the Data Source layer, leaving Domain and Presentation untouched.

An Android developer is configuring dependency injection using Hilt in Android Studio.

What are best practices for testing components in MVVM clean architecture?

Test each layer independently to keep your app reliable.

  • ViewModel tests: Mock UseCases and verify that the ViewModel updates LiveData or StateFlows correctly. Since ViewModels avoid Android-specific code like Context, they can be tested with plain unit tests.
  • UseCase tests: Mock Repositories to test business logic without depending on data sources.
  • Repository tests: Test with in-memory or fake data sources to verify data handling. You can also write integration tests using real databases or network mocks.
  • Data Source tests: These usually require integration or instrumentation tests, especially for databases or network APIs.

Keep tests focused on one layer at a time. Use interfaces and DI to swap real implementations with mocks or fakes easily. This isolation helps keep bugs contained and debugging faster.

Avoid Android-specific code in your domain layer to keep tests simple and fast.

Conclusion

Start by organizing your app into clear layers with specific roles, then implement each layer step-by-step. Use dependency injection to keep your code flexible and reactive streams like LiveData or Flow to connect layers cleanly. Writing tests for each layer helps you catch issues early and maintain separation of concerns. This setup takes some effort upfront but makes your app easier to maintain and extend as it grows.

Frequently Asked Questions

Can I use MVVM without clean architecture?

Yes, MVVM can be used alone. But combining it with clean architecture helps keep concerns separated and makes your app easier to scale and test.

Should I create a separate module for each layer?

It depends on your app size. Small apps often work fine with packages inside one module. Larger apps benefit from separate Gradle modules to enforce boundaries more strictly.

How do I handle UI state in MVVM clean architecture?

Use LiveData or Kotlin Flow in your ViewModel to expose UI state. The View observes these streams and updates automatically, keeping UI reactive and decoupled from business logic.

Read more