‫Hello, my friends, and welcome back.
‫In this video, we'll start learning about a very important concept in Android called ViewModel.
‫I want from you to fully focus with me.
‫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 activity or fragment with the rest of the application.
‫A ViewModel is always created in association with scope, a fragment or an activity and will be retained
‫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.
‫For example, rotation of the screen.
‫The ViewModel class is a business logic or screen level state holder.
‫It exposes state to the UI, to the user interface 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.
‫In the next video, we'll take an example about the ViewModel how to implement a ViewModel in our applications.
‫But let's jump into Android studio and see what our configuration changes.
‫I created this simple application called ViewModel Application to Text Views.
‫This is for title and this is the counter.
‫Also.
‫I have a button.
‫I include them inside the layout element and I add build features the data binding library to our application.
‫If you face duplicate class error in Android studio, just add fix duplicate class and this implementation
‫sync the project.
‫And let's move to the main activity.
‫In the main activity.
‫I created an activity main binding object called main binding and a counter of type integer.
‫Then initialize it and I need to increase the counter by one and set the text to the counter.
‫Run the project and you can see increase the counter.
‫It's increasing correctly.
‫But the problem if I click on turn and rotate the screen, you can see the counter is reset to the initial
‫value, which is zero.
‫Increase the counter.
‫It works perfect, but if I rotate the screen, the counter will be reset to its initial value.
‫This is a problem because our application is not surviving configuration changes, which is the rotation
‫screen.
‫In this case, what is the solution?
‫The solution is to use the ViewModel in our simple application.