Android MVVM Architecture
This article explains the MVVM (Model-View-ViewModel) architecture for modern Android development, detailing its three core components, their responsibilities, and provides a step‑by‑step example with Jetpack components, including LiveData, ViewModel, View Binding, and complete code snippets to build a simple user list UI.
Android MVVM Architecture
In modern Android development, maintaining a clear, testable, and modular codebase is essential. Google recommends the MVVM (Model-View-ViewModel) pattern, which embodies reactive programming principles. This article explores MVVM and demonstrates a simple implementation.
Overview of MVVM Architecture
MVVM consists of three core components:
Model – Represents the app’s data and business logic, such as network requests and database interactions.
View – Represents UI components, e.g., Activities and Fragments.
ViewModel – Mediates between View and Model, preparing data for the View and handling user interactions.
The responsibilities of each component are described below.
Model
The Model handles data processing and can be divided into:
Repository : Provides a data API, deciding whether to fetch from local database or network.
Local Data Source : e.g., SQLite or Room.
Remote Data Source : e.g., Retrofit or other networking libraries.
View
The View is what the user sees and interacts with. In Android it is typically an Activity or Fragment . The View only displays data and forwards user actions to the ViewModel, staying as “dumb” as possible.
ViewModel
The ViewModel supplies UI data. It does not request data directly but uses a Repository. It also does not reference the View; instead it notifies the UI of data changes via LiveData or other observer patterns.
Implementing MVVM
We will build a simple user‑list screen using the following Jetpack components: LiveData, ViewModel, and View Binding.
Step 1: Add Dependencies
In build.gradle (Module: app) add:
dependencies {
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
// View Binding
buildFeatures {
viewBinding true
}
}Step 2: Create Model
// User.java
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
// Getters and setters
public int getId() {
return id;
}
public String getName() {
return name;
}
}Step 3: Create ViewModel
// MainViewModel.java
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import java.util.Arrays;
import java.util.List;
public class MainViewModel extends ViewModel {
private MutableLiveData
> users = new MutableLiveData<>();
public MainViewModel() {
loadUsers();
}
public MutableLiveData
> getUsers() {
return users;
}
private void loadUsers() {
// Normally this would call the Repository layer
List
dummyUsers = Arrays.asList(new User(1, "Alice"), new User(2, "Bob"));
users.setValue(dummyUsers);
}
}Step 4: Create View
In activity_main.xml :
In MainActivity.kt use View Binding and ViewModel:
// MainActivity.kt
package com.example.myapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import com.example.myapp.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private MainViewModel mainViewModel;
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize View Binding
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Initialize ViewModel
mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
// Observe LiveData from ViewModel
mainViewModel.getUsers().observe(this, users -> {
// Update UI
StringBuilder userInfo = new StringBuilder();
for (User user : users) {
userInfo.append(user.getName()).append("\n");
}
binding.textView.setText(userInfo.toString());
});
}
}Remember that LiveData’s observation ensures UI updates only when the Activity or Fragment is in an active state.
Step 5: Test the App
Run the app and you will see the user list displayed in the TextView . This basic example shows how data flows from ViewModel to View without the View needing to know the data source.
Conclusion
MVVM is a powerful and flexible architecture that promotes separation and modularity. By leveraging LiveData and ViewModel, developers can create reactive apps that gracefully handle lifecycle events and data management. Using View Binding further simplifies UI code and eliminates the need for findViewById , reducing boilerplate and errors.
In practice you may also incorporate other Jetpack components such as Data Binding, Room, and Navigation to enhance efficiency and functionality.
We hope this tutorial helps you understand and start using MVVM architecture in your Android applications.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.