DEV Community

Hitesh Vijay
Hitesh Vijay

Posted on • Updated on

Android ViewModel Example




The ViewModel is part of Android JetPack and is used to effectively implement MVVM architecture pattern in android.

Why ViewModel?

MVVM architecture requires the activity to do minimum number of logical operations on the activity. That means we can do the logical operations needed for the View to be performed in ViewModel and then reference it in the Activities. Also ViewModel allows to observe LiveData in apps

Benefits

When we rotate the android device the activity is restarted an all the data is reloaded again. We can prevent this from happening if we are loading all the data in views from ViewModel class. An activity doesn't survive a state change while a ViewModel does.

Why can't just use a simple Kotlin/Java class

Some people might think that why can we use a simple Kotlin/Java class that does't extend ViewModel class to save the current state. The simple reason is that it won't survive state change. You can try the below example with a Kotlin/Java class.

Implementation

ViewModel class

class MainViewModel : ViewModel() {
    var number: Int = 0
    fun changeMainText(){
        number += 1
    }
}

Reference the view model class in activity

private lateinit var viewModel: MainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

Increment the number by calling

viewModel.changeMainText()

Get the value of the number

viewModel.number

This way we can save the data at state change without using some database. If you have any questions feel free ask me. If you learned something from this post please heart it❀

Oldest comments (1)

Collapse
 
golex12 profile image
golex12

Hello!

private lateinit var viewModel: MainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

ViewModelProviders' is deprecated!!!
developer.android.com/reference/ko...

You need to use something like this:
Isn't it?
private val viewModel: MainViewModel by lazy {
ViewModelProvider(this).get(MainViewModel::class.java)
}