All about ViewModel and Its working.

Hello friends hi. This post is regarding all about the ViewModel and It's working. 

Well, ViewModel is the part of the MVVM (Model-View-ViewModel) architectural pattern.

The ViewModel class is a business logic or screen level state holder. It exposes state to the UI and encapsulates related business logic. In more simple words, ViewModel is used to persist the state on configuration changes like Screen Rotation, Keypad show or hide etc.

It's a lifecycle aware component which means it work with respect to the lifecycle of an Activity or Fragment. Because it associated with Views as shown in following...


As we can see that the onCleared() method of the ViewModel is invoked just before the onDestroy() method of the Activity. 

The tasks which are no longer need in the memory is usually written in the onCleared() method of the ViewModel. Example:- Cancellation of a Coroutine.

Working of ViewModel:

There are three terms related to ViewModel to understand it's working...

1)- ViewModelStoreOwner Interface.

2)- ViewModelStore Instance.

3)- ViewModel Instance.


1)- ViewModelStoreOwner Interface- It is an Interface implemented by Component.

A responsibility of an implementation of this interface is to retain owned ViewModelStore during the configuration changes and call ViewModelStore.clear, when this scope is going to be destroyed.

2)- ViewModelStore Instance- It is a class to store the ViewModel.

Instances of ViewModelStore must be retained through configuration changes. If the owner of a ViewModelStore, typically a `ViewModelStoreOwner`, is destroyed and recreated due to a configuration change, the new owner must have the old instance of the ViewModelStore.

If the owner of a ViewModelStore is destroyed and is not going to be recreated, it should call `clear` on this ViewModelStore so that The ViewModel stored by it are notified that they are no longer needed.

3)- ViewModel Instance- This class is whole responsible for persisting the data on configuration changes. 


The whole working can be explained in more simple words sing the following diagram....



a)- ViewModelProvider create the Instance of ViewModel (If not created earlier) ------>

b)- ViewModelStore checks if the ViewModel instance is available or not ------->

c)- If ViewModel instance is available then return the instance with latest state -------->

d)- else get the new ViewModel instance and return it to the ViewModelStore. ------>

e)- Then ViewModelStore return the ViewModel instance to the ViewModelProvider or ViewModelStoreOwner --------> 

f)- Then finally the component gets the ViewModel with saved state of data.

 


Thank You :)

Comments

Popular posts from this blog

All about Fragment in Android

Architectural patterns in Software Engineering