MVVM Architecture using Repository pattern for beginners

Abhishek Pathak
7 min readSep 15, 2022

--

Software architecture is probably one of the most popular topics among developers, regardless of the platform you build for. With all the available frameworks and tools for asynchronous programming, dependency injection, networking, data caching and view-bindings, many patterns have evolved and some have stood out from the bunch. I found MVVM is best among all for Android development.

MVVM (Model-View-ViewModel) is a software design pattern that is structured to separate program logic and user interface controls. MVVM is also known as model-view-binder and was created by Microsoft architects Ken Cooper and John Gossman.

MVP DRAWBACKS is the main reason to move to MVP to MVVM

The first problem is the tight-coupling between the View and the Presenter. Each View holds a reference to the Presenter and each Presenter holds a reference to the View. In order for the two layers to communicate, a communication channel has to be opened via the Contract. This approach results in less-generic code (since the Presenter can’t be used as a layer in the MVP triad for another View). In a heap of communication methods, both the View and the Presenter will rapidly expand in the code-line size. There is also an extra layer of difficulty while writing unit tests, since there is a View dependency in each Presenter.

So what is the solution to avoid MVP problems? First thing comes in my mind is MVVM as it allow a lot benefit and most flexible architecture app. Let’s learn about MVVM now.

MVVM stands for Model View ViewModel and it also contains other Android jetpack components like livedata, UI etc.

MVVM architecture layer components

  • Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data. This layer contains Remote sources as well as local sources.
  • View layer (activity/fragment) : The purpose of this layer is to interact with the ViewModel about the user’s action. This layer observes the livedata changes and does not contain any kind of application logic to keep UI layer neat and clean.
  • ViewModel: The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The viewmodel class allows data to survive configuration changes such as screen rotations (no need to handle screen orientation data manually)

How MVVM works?

The complete flow is as follows: there is a View on top, which only has a dependency to ViewModel. Since there is no longer a one-to-one relationship between the View and (formerly) the Presenter, it is now possible to couple multiple ViewModels to any View, since a ViewModel contains no View references. A ViewModel depends on repositories for fetching/caching data, and a repository will depend on a local and/or remote data source. In testing jargon, there is only one layer beneath the one you’re about to test, that you should mock (with the exception of a repository). Finally, since the states/data is exposed to its listeners via “LiveData”, we get auto-UI updates by simply observing it.

Advantage of using MVVM

  • Maintainability

A clean separation of different kinds of code should make it easier to go into one or several of those more granular and focused parts and make changes without worrying. That means you can remain agile and keep moving out to new releases quickly.

  • Testability

With MVVM each piece of code is more granular and if it is implemented right your external and internal dependences are in separate pieces of code from the parts with the core logic that you would like to test. That makes it a lot easier to write unit tests against a core logic.

  • Extensibility

It sometimes overlaps with maintainability, because of the clean separation boundaries and more granular pieces of code. You have a better chance of making any of those parts more reusable. It has also the ability to replace or add new pieces of code that do similar things into the right places in the architecture.

Let’s discuss about ViewModel, Core part of MVVM architecture

ViewModel is a class that is responsible for preparing and managing the data for an Activity or Fragments. View Model is the replacement of Presenter(of MVP architecture). It also handles the communication of the Activity/Fragment with the rest of the application (example- calling the business logic classes). ViewModel contains liveData that is lifecycle aware so that viewmodel help to avoid runtime crashes happened due to screen rotation.

The lifecycle of a ViewModel when device got rotated

This is the beauty of View model that survives during orientation changes.

In the lifecycle diagram after rotation activity got recreated so onCreate() after that onStart() then onResume() but when we rotate the screen our activity is destroyed and after rotation again system calls onCreate() and other functions one after another. As our activity destroyed our activity data has also vanished.

What is ViewModel Factory?

ViewModel Factory is based on Factory Design Pattern where you want similar products i.e. view models for it. It helps the ViewModel to live independently rather than dependent on some Views like Fragments or Activities to instantiate them.

To instantiate ViewModel we have 2 ways.
Way 1 : we can instantiate using Activity or Fragment as owner of ViewModel

Way 2 : We can instantiate using ViewModelFactory.

Benefit of using View Model Factory is saving the unexpected crashes happened to Activities and that will also lead to loss of data as you viewmodel also being vanished out.

fun <T : ViewModel> T.createFactory(): ViewModelProvider.Factory {
val viewModel = this
return object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T = viewModel as T
}
}

In app.gradle use this scipt

kotlinOptions {
freeCompilerArgs = ['-Xjvm-default=enable']
}

How to use this factory for viewmodel instantiation

val factory = MainViewModel(apiService).createFactory()
val viewModel = ViewModelProvider(this, factory)[MainViewModel::class.java]

What is LiveData?

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state. It is part of Android Jetpack component.

Types of LiveData

  • LiveData is immutable by default. By using LiveData we can only observe the data and cannot set the data.
  • MutableLiveData is mutable and is a subclass of LiveData. In MutableLiveData we can observe and set the values using postValue() and setValue() methods (thread-safe) so that we can dispatch values to any live or active observers.
  • MediatorLiveData can observe other LiveData objects such as sources and react to their onChange() events. MediatorLiveData will give us control over when we want to perform an action in particular or when we want to propagate an event.

Advantages of LiveData

  • Ensures your UI matches your data state
  • No memory leaks
  • No crashes due to stopped activities
  • No more manual lifecycle handling
  • Always up to date data
  • Proper configuration changes
  • Sharing resources

ObservableField vs LiveData

Observable Field is not lifecycle Aware and LiveData is lifecycle aware, hence it is prefer to use livedata over Observable Field to take MVVM fully advantageous.

Repository pattern in MVVM

The Repository pattern. Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.

Why Repository Pattern ?

  • Decouples the application from the data sources.
  • Provides data from multiple sources (Local, Remote, Cache) without clients being concerned about this.
  • Isolates the data layer.
  • Single place, centralized, consistent access to data.
  • Testable business logic via Unit Tests.

CONCLUSION

Is MVP bad? No, then Is MVVM better?

It depends. For our needs and the complexity of applications we create, MVVM should help us get rid off some drawbacks MVP. On the other hand, new drawbacks regarding MVVM will appear, and we have to be ready to manage them since the benefits of a well-designed architecture will always minify the disadvantages.

Here is my sample app using MVVM architecture having repository pattern.

Thanks for reading this article. Be sure to click 👏 below to applause this article if you found it helpful. It means a lot to me.

--

--