MVVM — Android App Architecture — Part 2

Elvin Akhundzada
5 min readJul 19, 2023

--

In this article, we will explore the MVVM (Model-View-ViewModel) architecture in Android app development. Before delving into MVVM, let’s review the primary limitations of the MVP (Model-View-Presenter) architecture discussed in our previous blog post on app architectures in Android:

  1. Strong coupling between View and Presenter: In MVP, the View and Presenter are tightly coupled, leading to code complexity and difficulties in testing.
  2. Lack of lifecycle awareness in the Presenter: MVP lacks built-in lifecycle awareness for the Presenter, making it challenging to handle configuration changes and resource management effectively.
  3. Inability for the View to observe model updates: In MVP, the View is responsible for displaying data but cannot directly listen to updates from the Model, resulting in additional code for synchronization.

Fortunately, MVVM architecture resolves these issues and provides a more robust and maintainable solution. Now, let’s delve into MVVM by addressing each of these drawbacks individually.

Model:

In MVVM, the Model component represents the data and business logic of the application. It encompasses databases, network requests, repositories, and other data-related operations. Its responsibility lies in manipulating, fetching, and retrieving data.

View:

The View component in MVVM is similar to MVP, as it represents the UI components such as Activities or Fragments. It focuses on displaying data to the user and capturing user interactions.

ViewModel:

The ViewModel acts as a mediator between the Model and View in MVVM. It holds UI-related data fetched from or sent to the Model. The ViewModel’s responsibilities include handling user interactions and triggering corresponding actions in the Model.

According to Google’s official documentation, ViewModel is defined as a Business logic or screen-level state holder. It exposes state to the UI and encapsulates related business logic. One of its primary advantages is caching state and persisting it through configuration changes.

In other words, using MVVM we can avoid fetching the data and populating it again when:

  1. Device configuration changes.
  2. User navigates to another activity/fragment.
  3. Activity is moved to background. *

* When the application is terminated by the system, such as during low memory conditions, the existing ViewModel instances also will be destroyed. So will the data that ViewModel holds. To avoid such cases, we should persist our necessary data in local database, SharedPreferences etc. Otherwise, we’ll have to restore the data back from storage or remote source.

ViewModel lifecycle.

Creating ViewModel

To create a ViewModel instance, we need to extend the ViewModel class and pass a ViewModelStoreOwner (such as an Activity, Fragment, or navigation destination) to the ViewModelProvider within the onCreate() method of the Activity or Fragment. This ensures the ViewModel’s lifespan aligns with that of the associated object in memory.

MvvmActivity.kt

It’s worth noting that, by default, we cannot pass arguments to the ViewModel constructor. To have a ViewModel that accepts arguments, a custom ViewModelFactory is required. We will cover ViewModelFactory in a separate article dedicated to ViewModel.

Once the ViewModel is set up, the next step involves creating a repository class responsible for interacting with the ViewModel and forwarding/fetching data to/from a local or remote data source. Ideally, data should be stored in a data holder class, such as a local database, remote API, SharedPreferences, or a file. To make it simple we’ll store our data in a data holder class that will contain the list items which will be deleted when our activity gets destroyed. But ideally it will probably be one of the list above.

Connecting View & ViewModel

The ViewModel stores data in observable data holders, such as LiveData or StateFlow, which the View observes and reacts to accordingly.

MovieViewModel.kt

Next, we’ll add the code to listen the updates from our ViewModel:

Advantages of MVVM

  1. Clear separation of concerns: MVVM ensures a clear separation between the ViewModel and View. The ViewModel remains unaware of the View’s implementation details, promoting better code organization and testability.
  2. Automated state handling: MVVM simplifies state handling after configuration changes and navigation. The ViewModel retains data, resulting in a seamless user experience.
  3. View observes UI-related data: The View exclusively observes UI-related data from the ViewModel, reducing the complexity of data synchronization and ensuring a reactive UI.

If you remember, these 3 points were exactly the ones that MVP couldn’t provide for us! 🥳

What to avoid when using ViewModel ?

  1. Keeping separate UI component state in ViewModel: It is recommended to limit the ViewModel’s scope to holding screen-level data. Avoid mixing separate UI component states within the ViewModel.
  2. ViewModel should remain unaware of activity or fragment details: The ViewModel should not have direct knowledge of the activity or fragment lifecycle or other specific implementation details. This ensures loose coupling and maintainability.
  3. Avoid passing lifecycle-related APIs to ViewModel: Refrain from sending or storing lifecycle-related APIs, such as the Context, in the ViewModel. Doing so may lead to memory leaks, as these APIs can potentially outlive their owner.
  4. Keep the ViewModel closely associated with the View: As ViewModels are managed by the operating system, avoid passing ViewModels as constructor or method arguments. Keep the ViewModel tightly associated with its corresponding View.

You can refer to this link for the full sample code.

This article provided an overview of the MVVM architecture in Android app development, focusing on understanding MVVM and its advantages over MVP. In future articles, we will expand on this sample Movie application by covering topics such as Room, DI (Dependency Injection), Coroutines and more.

Stay tuned for more in-depth discussions on implementing MVVM and related technologies to enhance your Android app development skills.
Happy coding! ✌🏻

--

--