From the course: Android Development Essential Training: 3 Navigation

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Store and publish data in a ViewModel

Store and publish data in a ViewModel - Android Tutorial

From the course: Android Development Essential Training: 3 Navigation

Start my 1-month free trial

Store and publish data in a ViewModel

- [Instructor] ViewModels allow you to store and manage UI data in a lifecycle conscious way. Since they're retained during configuration changes, like rotating your device, you won't have to worry about losing your UI-related data. Let's modify our main ViewModel to store some data for us. We're going to create a private immutable variable, named _info, and it's going to be of type MutableLiveData. We'll do that here right at the beginning of our class. It's going to be, private val _info, it's going to be of type MutableLiveData, and we want it to store an integer. Next, we just need to initialize our variable, and we're done. We're choosing to make this variable private because we only want the ViewModel to be able to store and publish changes to it, no outside classes. Next, in our initialization block, we'll set the value of our MutableLiveData to a zero in order to start. We'll come here underneath where we have our log…

Contents