Android Architecture Patterns Part 1: Model-View-ViewModel

Burak iren
2 min readSep 11, 2019

--

Mvvm is an architectural pattern for seperating program logic and user interface controls. It consist 3 mainly part: Model, View, View Model.

Model

Model represents the business objects that encapsulate the data and behavior of application domain. It usually sends the data to the ViewMode l.If you are building an application for finding flights, your application domain model includes classes like flight, location, time.

View

View is the collection of visible elements, which also receives user input. This includes user interfaces (UI), animations and text. Sends data only to ViewModel.

ViewModel

ViewModel provides communication between model and View. It is a class with properties that represent the state of the view and methods that implement the logic behind the view.

The following diagram shows MVVM components and basic interactions.

The ViewModel is always created in close relation to a specific scope, either an Activity or Fragment. The scope is retained as long as the Activity or Fragment is alive. In practical terms, the ViewModel reconnects with the view after configuration changes, maintaining itself until the main view is destroyed. According to the official documentation:

There are two ways to implement a ViewModel. The standard one is to extend the class, providing a no-argument constructor. This is the easiest way, but it doesn't work well with Dependency Injection.

class MainViewModel : ViewModel() {
init {
// initialize some behavior
}

fun getData() : LiveData<String> {
// get some data
}

override fun onCleared() {
super.onCleared()
// called before its destruction
}
}

In another article, we will learn how to use Mvvm with LiveData on an example.

See you later :)

--

--

Burak iren
Burak iren

Written by Burak iren

Learner, Android Developer @DeliveryHero

Responses (1)