4 Steps to MVVM in Android (Kotlin)

Kashif Anwaar
2 min readOct 24, 2019

--

Kotlin version of the easiest guide to MVVM.

This guide is also available in Java https://medium.com/@kashifo/4-steps-to-mvvm-in-android-java-b05fb4148523

I felt that nobody has explained MVVM in an easy way with a simple example, so I decided to write this article. I am going to create a very simple app to demonstrate it, I am going to fetch U.S public holidays from a public API and display it in recycler view.

The 4 steps of MVVM

  1. Create Model (aka POJO)
  2. Create Repository (fetch data from API or DB)
  3. Create ViewModel (extend ViewModel, get liveData from Repository)
  4. Create Activity (observe ViewModel & display data)

I hope you are using AndroidX and applied ‘kotlin-android-extensions’ plugin in your project, if not check this project’s source on Github. Let’s get started.

Step1: Create Model (aka POJO)

Let’s create a Pojo class to store the value of each holiday.

Step 2: Create Repository

A repository is a class where we fetch data from API or DB.

In the repository create a MutableLiveData variable.

var mutableList: MutableLiveData<ArrayList<HolidayModelKotlin>> = MutableLiveData()

Fetch data from API and set the data into the LiveData variable.

mutableList.value = response.body()!!

Here’s the full example of a repository.

In the example, I’m using Retrofit to fetch public holiday list

Step 3: Create ViewModel

ViewModel is just a class created by extending ViewModel to hold data, the official definition is

The ViewModel class is designed to hold and manage UI-related data in a life-cycle conscious way. This allows data to survive configuration changes such as screen rotations.

To create a ViewModel, extend a class with ViewModel, initialize the repository object in the constructor, create ViewModel variable, create a getter method to fetch the value from the repository and set it into ViewModel.

Step 4: Create Activity

In Activity create an object of ViewModel, call the getter method and observe the data using LiveData as shown below.

Whenever data is changed you’ll get a callback in the onChanged method. Inside the onChanged method I’m setting the ArrayList to my adapter.

To view the complete code, check the ‘kotlin’ package in this project on Github.

--

--

Kashif Anwaar

Technologist, Products & Startup Enthusiast, Passionate Software Developer active in Android development.