Understanding the Flow of Data in MVVM Architecture
Tags: android, architecture, mvvm
Published: 2019-08-20 18:51:47

Often we need to pass data around or establish communication between different views in an application. MVVM architecture makes this easy when developing Android apps, however some of the concepts might appear a little bit confusing at first. Sometimes there is some misunderstanding around the role of views or view models and how they should be used in relation to each other. This article will demonstrate the interaction between the different components of an MVVM architected Android app in order to help you gain a clear understanding of the flow of data.

### **The *Observer* design pattern is the first key to understanding the flow of data in MVVM**

The Observer pattern allows one or more *observers* of data to be updated by an *observable* or *subject*. In an MVVM architected app the use of this pattern facilitates the flow of data between different components (Model, View-Model & View) and keeping these layers separate.

The *Observer* pattern forms the basis of the *Observable* base class in libraries such as RxJava and Android's own *LiveData* class as part of Android Architecture Components. Observers of data are usually views and sometimes view models, and observables are normally defined in the model or view-model layer. The model itself can also be an observer of data to perform any backend processing.

### **Asynchronous model of data flows using observable streams**

This is the second key to understanding the flow of data in MVVM, as opposed to the usual way of calling a function and expecting a result via a return statement or a callback function being invoked.

The result of the operation can be observed by registering an observer with an observable defined in the model of the application. This facilitates continuous data updates until the view is destroyed.

It is important to note that synchronous requests still have their place in an MVVM app, e.g. to quickly obtain the state of something such as checking an app setting.

It is generally better practice however, to program using asynchronous flows. For example changing the logic of a data lookup from memory to network or database (both of which require background execution) means only the model implementation needs to be changed and the view and view model code remains the same.

## Overview of Interaction Between MVVM Components

In order to understand how data should flow in an MVVM app we should first look at a high-level overview of the relationship between the different components and how they interact with one another.

![MVVM_Data_Flows_1.png] (https://thepracticaldev.s3.amazonaws.com/i/r82oczwhgpxhtxnk1r7a.png)

***Figure 1** - shows a conceptual application and possible interaction between MVVM components*

**In MVVM architecture, the view interacts with the view-model for data binding, and the view model talks to the model. The view never interacts with the model directly. In essence, view-models facilitate interaction between the application model and views.**

There are some other important points that can be derived:

- Views should never communicate directly with each other and all data should be passed through view models (It's even better to define view state as a data model and process or save it in the model, even if it's transient).
- Views (e.g. activity, fragment, Android view) can bind to one or more view models.
- View models can bind to one or more models.
- Models can interact directly with each other. This can be achieved via shared components such as a database, preferences or shared objects in memory.

Let's move on to looking at the interaction between MVVM components in more detail. These interactions are presented separately to provide a clearer view of how things work.

## View and View-Model Interaction

![MVVM_Data_Flows_2.png](https://thepracticaldev.s3.amazonaws.com/i/qt4e8hrkrfy6kjxztevd.png)

***Figure 2** - the sequence of interactions between a view and a view-model in an Android application*

**1. Obtain instance of view model** - this should normally happen during view creation, e.g. *Activity.onCreate()* or *Fragment.onCreate()*. In Android Architecture components this is achieved by a call to the *ViewModelProviders.of()* function.

**2. Start observing data** - the view starts to observe data updates by registering an *observer function* or *callback* with an observable in the view model such as a *LiveData* instance. This lasts for the duration of the lifecycle of the view. The Android *LiveData* class automatically takes care of this.

**3. Get or set data** - send a request to the view model to either get some data or make some changes (or even create something) via exposed functions or properties.

**4. Update the view** - when the observable (e.g. LiveData instance) has it's value updated with a result, it calls the registered observer so that the view can be updated. 

## View-Model and Model interaction

![MVVM_Data_Flows_3.png](https://thepracticaldev.s3.amazonaws.com/i/f0rsper9esl25ocqffz0.png)

***Figure 3** - the sequence of interactions between a view-model and a model in an Android application*

**1. Obtain instance of model** - when the view model is created a reference to the model should be obtained via dependency injection or accessing the model singleton or otherwise. Release any references to model properties such as unregistering from observables when the view model is destroyed, e.g. *ViewModel.onCleared()*.

**2. Start observing data** - the view model subscribes to data updates from the model. This can be something like subscribing to an RxJava *Observable* or it can be a direct reference to a LiveData instance defined in the model

**3. Get or set data** - when a view model function is invoked by a view, the view model may do some internal processing but will generally forward the request to the model on behalf of the view.

**4. Update the observer** - once the model has performed its processing it updates the relevant observable. If an RxJava Observable is updated this will normally result in a live data instance being updated in the view model. Since one or more views may have observed the live data instance they will get notified and be updated accordingly.

## Closing Comments

MVVM architecture neatly facilitates the flow of data between different views and models in Android application. The introduction of Android Architecture Components  has made implementing a decent MVVM app architecture much easier. 

The key things to understand in order to successfully implement the flow of data in an MVVM architected app are:

- The Observer design pattern *(and core classes such as Architecture Components LiveData and/or Observable in Rx Observable and LiveData)*
- Asynchronous nature of data flows *(achieved by separating requests to the model and observing the result via an observable)*
- View and view-model interaction
- Lifecycle of views and view-models
- View-model and model interaction

Once the flow of data is understood, you can make informed decisions in defining your views, models and view-models and implementing the interactions between them resulting in a well structured and clean codebase.

## Subscribe
This article was [originally published](https://www.productivebot.com/posts/understanding-the-flow-of-data-in-mvvm/) on my website [ProductiveBot.com](https://www.productivebot.com/). If you liked this article be sure to subscribe on the ProductiveBot website to get notified when I publish new content.