‫Hello developers, and welcome back.
‫In this section we're going to learn about two very important concepts in Android, which are the Viewmodels
‫and LiveData.
‫I want from you to fully focus with me because these are the building blocks for the next videos and
‫sections, and they are very important.
‫ViewModel is a class that is responsible for preparing and managing the data for an activity or a fragment.
‫It also handles the communication of the activity or fragment with the rest of the application.
‫The ViewModel is always created in association with a scope, a fragment, or an activity and will be
‫retained.
‫It will be preserved as long as the scope is alive.
‫For example, if it is an activity until it is finished.
‫In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration
‫change and the configuration change, maybe the rotation of the screen.
‫Don't worry, I'll show you in real example in this video how the configuration change happens.
‫The ViewModel class is a business logic or screen level state holder.
‫It exposes a state to a UI and encapsulates related business logic.
‫Its principal advantage is that it caches a state and persists it through configuration changes.
‫This means that your UI doesn't have to fetch data again when navigating between activities or following
‫configuration changes, such as when rotating the screen.
‫Let's jump into Android Studio.
‫I created a new project in Android Studio called Viewmodels app, and here in the build.gradle dot css
‫file I enabled data binding.
‫I created the simple layout one text view for title and I included the layout tag, another button and
‫text view.
‫This is for the result and this ID is text view two.
‫If we move to the main activity, we have a counter.
‫Here counter variable equals to zero and I initialized this binding.
‫So we can remove this Setcontentview method.
‫And I set it to R dot layout dot activity main.
‫And here I used binding dot button dot set onclicklistener I increased the counter and set the new text
‫with the new counter value.
‫If we run the application, this is our great application.
‫Increase the counter and if you click the counter will increase.
‫But the problem here is the configuration changes.
‫If I click on the rotate left or right buttons to rotate the screen, you can see the screen is rotated
‫and the counter is reset to zero.
‫If I increase the counter, everything will work fine.
‫If I rotate the device again, it will forget the last counter state.
‫So this is the configuration changes.
‫This is a real problem if the user rotates the screen.
‫I need to save these states.
‫I need to to save that the counter was on five before he rotates the screen.
‫The solution of this problem is by using the ViewModel.