Home Android & Kotlin Books Advanced Android App Architecture

10
Model View ViewModel Theory Written by Aldo Olivares

In this chapter you will learn about a distant relative of MVP — the MVVM Architecture Pattern.

First, you will explore how MVVM works at a high level. You will learn about each of its layers and how they communicate between each other. You will also learn how MVVM improves the testability of your apps by providing a clear level of abstraction to your code.

Finally, you will understand the advantages and limitations of MVVM to know when and how to apply it properly.

Ready? Let’s get started!

The Model-View-ViewModel pattern

MVVM stands for Model-View-ViewModel. MVVM is an architectural pattern whose main purpose is to achieve separation of concerns through a clear distinction between the roles of each of its layers:

  • View displays the UI and informs the other layers about user actions.
  • ViewModel exposes information to the View.
  • Model retrieves information from your datasource and exposes it to the ViewModels.

At first glance, MVVM looks a lot like the MVP and MVC architecture patterns from the last chapters.

The main difference between MVVM and those patterns is that there is a strong emphasis that the ViewModel should not contain any references to Views. The ViewModel only provides information and it is not interested in what consumes it. This makes it easy to create a one-to-many relationship wherein your Views can request information from any ViewModel they need.

Also of note regarding the MVVM architecture pattern is that the ViewModel is also responsible for exposing events that the Views can observe. Those events can be as simple as a new user in your Database or even an update to a whole list of a movie catalog. Now, you will explore how each of the MVVM layers work one by one.

The Model

The Model, better known as DataModel, is in charge of exposing relevant data to your ViewModels in a way that is easy to consume. It should also receive any events from the ViewModel that it needs to create, read, update or delete any necessary data from the backend.

The ViewModel

The ViewModel retrieves the necessary information from the Model, applies the necessary operations and exposes any relevant data for the Views.

The View

The View is what most of us are already familiar with, and it is the only component that the end user really interacts with. The View is responsible for displaying the interface, and it is usually represented in Android as Activities or Fragments. Its main role in the MVVM pattern is to observe one or more ViewModels to obtain the necessary information it needs and update the UI accordingly.

MVVM by example

The next two chapters will cover practical examples of MVVM. You will learn how to rewrite the Movies app with two different approaches: Using architecture components and using Data Binding.

class MainViewModel: ViewModel() {

  //1
  private var items: LiveData<List<Item>>? = null
  //2
  fun getItems(): LiveData<List<Item>> {
    if (items == null) {
      return db.itemDao().getAll()
    }
    return items ?: emptyList()
  }
}

class MainActivity: AppCompatActivity() {

  //3
  private lateinit var mainViewModel: MainViewModel

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    //4
    mainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

    //5
    recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
    val adapter = ItemAdapter()
    recyclerView.adapter = adapter

    //6
    mainViewModel.getItems().observe(this, Observer {
      if (it != null) {
        adapter.list.clear()
        adapter.list.addAll(it)
        adapter.notifyDataSetChanged()
      }
    })
}

MVVM advantages and concerns

One problem that the MVC architecture patterns have in common is that the Controllers and the Presenters are sometimes very hard to test due to their close relationship with the View layer. By handling all data manipulation to ViewModels, unit testing becomes very easy since they don’t have any reference to the Views.

MVVM vs. MVC vs. MVP

You might be wondering why you would want to use MVVM over MVC or MVP. After all, MVC and MVP are among the most common Android architecture patterns and are both very easy to understand. There has been endless debate on which approach is best, but the answer largely boils down to personal preference.

Key points

  • MVVM stands for Model-View-ViewModel.
  • MVVM is an architecture pattern whose main objective is the separation of concerns.
  • Views display the UI and inform about user actions.
  • The ViewModel gets the information from your Data Model, applies the necessary operations and exposes the relevant data to your Views.
  • The ViewModel exposes backend events to the Views so they can react accordingly.
  • The Model, also known as the DataModel, retrieves information from your backend and makes it available to your ViewModels.
  • MVVM facilitates Unit Testing of your code.
  • MVVM may be too complex for applications with simple UI.

Where to go from here?

There are several patterns that you could use to build your Android Apps. The Model-View-ViewModel architecture pattern is just one of the many tools that helps you write clear and concise code. But MVVM combines the advantages of the MVP and MVC architecture patterns with other useful features such as DataBinding. It improves the testability of your code by providing a greater level of abstraction and reducing the amount of boiler plate code in your projects.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.