ViewModel: What, Why & How?(Part-2)

Harjot Singh
HealthifyMe Tech
Published in
3 min readMar 6, 2022

If you haven’t read Part 1, I’d suggest please go through it to get a basic understanding of ViewModel. Here’s the link to it.

https://medium.com/@harjotsingh01/viewmodel-what-why-how-part-1-3cd9ac479f7f

What we’ll be making:

This sample was created just to explain the fact that the data inside ViewModel can survive configuration changes w/o losing the data(rotation of screen for this example).

Let’s understand the how now…

Step 1: Create a basic XML layout like this:

So, one Button and one TextView.

Here’s the XML code for you to save time:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/tv_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/_0"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="@string/add"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tv_score" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 2: Create your ViewModel class

class MainViewModel : ViewModel() {
private val _score = MutableLiveData<Int>(0)
val score: LiveData<Int> = _score
fun addScore() {
_score.value = _score.value?.plus(1)
}
}

In this code snippet, MainViewModel extends ViewModel class. We have a _score variable as MutableLiveData(with initial value as zero) i.e. it’s value can be changed, since it’s mutable. The type we are using for mutable live data is that of Int, the reason being score will be a Int value.

Then addScore() is the functionality for button click. It adds one to the _score every time user clicks on ADD button.

If you don’t know how to work with LiveData, I’d suggest to go through the above article too but for now let’s just copy the code.

Step 3: Add the functionality in your MainActivity.java file

Since, ViewBinding is used here, let’s add the code required to use it in the module level gradle file.

//Add this inside android code block : android {...}
buildFeatures{
viewBinding true
}

Let’s go through the code now…


class MainActivity : AppCompatActivity() {
private val binding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
// a. initialising viewModel
viewModel = ViewModelProvider(this)
.get(MainViewModel::class.java)
val scoreText = binding.tvScore
val addBtn = binding.btnAdd
// b. button functionality
addBtn.setOnClickListener {
viewModel.addScore()
}
//c. Observing the live data
viewModel.score.observe(this) { score ->
scoreText.text = score.toString()
}

}
}

Confusing…? Okay, let’s go through it point by point:

a. Initialising ViewModel
ViewModelProvider
is a class that creates ViewModels and retain them in a store of given ViewModelStoreOwner. Here, we’ve passed this as the owner.

b. Button functionality
Here, we called out a method from viewModel, basically doing separation of concerns. This method adds one to the existing score.

c. Observing the LiveData
Now, we are simply observing the changes that would happen inside LiveData.

For a better understanding, here’s how the flow works:

Thank you for reading!
Here’s part -1 of this story:

https://medium.com/@harjotsingh01/viewmodel-what-why-how-part-1-3cd9ac479f7f

--

--

Harjot Singh
HealthifyMe Tech

Android Developer @HealhifyMe I lose my handwritten notes often...so now making sure I can find my notes easily :p