🤖Basic Android ViewModel in 5 minutes

Michael M.H
5 min readSep 15, 2022

--

Hi, this is Michael again!👋 Today, I wanted to write about MVVM. But first, I thought it might be better to introduce you with ViewModel. Why? If you read the sample source for MVVM, many times it`s all mixed with various Jetpack libraries such as ViewModel, LiveData, Data Binding, Room, Dagger 2, etc. Which might confuse you, especially if you are a beginner. Don`t worry, I will try to explain it to you as easy as possible.

So What is ViewModel

⭐To make it simple, ViewModel is one of the components included in Android Jetpack. A ViewModel object contains data-handling business logic to interact with the model and delivers the data for a particular UI component, such a fragment or activity. In other words, it`s just an interface between UI and the data.

🔗https://www.youtube.com/watch?v=5qlIPTDE274&t=34s

In Activity and Fragment, for example, when the screen is rotated, it is recreated, so the temporary data managed by these event will be lost.
However, by using ViewModel, you can inherit(keep) the data even if you rotate the screen.

In addition, it corresponds to the VM (ViewModel) part when developing with MVVM architecture. The relationship between a View (Activity, Fragment, etc.) and a ViewModel is as follows.

Life-cycle of ViewModel❓

The ViewModel is designed to have a longer life than the target LifecycleOwners(An interface called LifecycleOwner is implemented by a class that owns or retains something and runs it through a recognized lifetime, such Activities and Fragments).

Even if an Activity or Fragment is recreated by screen rotation, the ViewModel will still be alive and still be able to hold the data.
The lifecycle of a ViewModel is as follows:

https://developer.android.com/topic/libraries/architecture/viewmodel

🤖 I will make a simple app that uses ViewModel so follow along!
Let`s make an app that adds two numbers (values a and b), which will output the result on the screen when the calculate button is clicked.

  1. ⚙️First, open the build.gradle(app) file and add following implementation to the dependencies block as follows :
def lifecycle_version = "2.3.1"// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"

2. 🤖Creating a ViewModel
Add the Kotlin Class to the java folder. This time, I will name it CalculationViewModel. All you have to do is to extend the ViewModel() class. Boom it`s a ViewModel!

class CalculationViewModel(private val calculations: Calculations) : ViewModel() {
// Write the logic in here
}

⚙️I will create a separate interface called Calculations that I will set it as an argument in the CalculationViewModel. This interface will contain a function called calculateAddition, which will perform the addition. I will use it in CalculationViewModel. Just to let you know, This is just my way of doing it. It`s not related to ViewModel.

interface Calculations {
fun calculateAddition(a: Int, b: Int): Int
}

3. ⚙️This is not necessarily a must-do task, but creating a ViewModelFactory that generates a ViewModel is a good practice. So, let`s create a class that extends ViewModelProvider.Factory. I will name it CalculationViewModelFactory. We will be using this class later in the MainActivity, when passing this class into the ViewModelProvider.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

class CalculationViewModelFactory(
private val calculations: Calculations
) : ViewModelProvider.Factory {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return CalculationViewModel(calculations) as T
}
}

4. ⚙️Next create a class(I named it “MyCalculation”) that will inherit from the Calculation interface that we created in step 2. We would then override the function calculateAddition() and in there, we will write a simple addition logic that returns the result.

class MyCalculation : Calculations {
override fun calculateAddition(a: Int, b: Int): Int {
return a + b
}
}

5. ⚙️Next, we will go back to the CalculationViewModel, and start adding the logics and the parts(Such as MutableLiveData for binding, function to check if the values for a and b are not null, calling calculateAddition(), ect) that we will need.

Forgive me for the messy code, it`s just for testing purpose. You can try applying some better ways and play around with it.

6. ⚙️After setting up the ViewModel, let`s create the layout. We will be using Databinding. If you are not familiar with Databinding, it might be better to check them out first.

Displays variables
android:text=”@={myViewModel.a}”
Executes a function
android:onClick=”@{()->myViewModel.calculateAddition()}”

We will bind the variable from ViewModel. ⚠ ️Check the bolded section below.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="myViewModel"
type="com.yourpackagename.CalculationViewModel" />

</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:orientation="vertical"
tools:context=".MainActivity" >

<EditText
android:id="@+id/a_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:text="@={myViewModel.a}"
android:hint="a value"
android:inputType="number"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:textStyle="bold" />

<EditText
android:id="@+id/b_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:text="@={myViewModel.b}"
android:hint="b value"
android:inputType="number"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:textStyle="bold" />

<Button
android:id="@+id/calculate_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/calculate"
android:layout_marginBottom="15dp"
android:onClick="@{()->myViewModel.calculateAddition()}"
android:textSize="20sp"
android:textStyle="bold" />

<TextView
android:id="@+id/addition_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:text="@={myViewModel.additionResult}"
android:gravity="center_horizontal"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</layout>

7. Finally, go to the MainActivity and setup as the following. I assume, that it`s quite straight forward. Technically, we are jacking up all the parts that we created in the previous steps.

⭐If you were able to run the project successfully, I assume that you will be able to get the result like the following.

Thank you for reading until the end! 🤖

--

--

Michael M.H

🥋 Karate Instructor / 🤖Mobile developer / 👨‍💻 IT Consultant / 🎮 Creator / FX Crypto Trader Bro