'How does the Android Viewmodel works internally, internal working of view model

How does the Android Viewmodel works internally?

How Viewmodel save the data when the activity gets destroyed and recreated when the device get rotated



Solution 1:[1]

How does the Android Viewmodel works internally?

Android's ViewModel is designed to store and manage UI-related data in such a way that it can survive configuration changes such as screen rotations.

ViewModel gets called by an activity that previously called it, it re-uses the instance of that ViewModel object. However, if the Activity gets destroyed or finished, counterpart ViewModel calls the onClear() method for clearing up resources. Meaning if you have added something like this to your ViewModel:

override fun onClear() {
   super.onClear()
   clearAllLiveDataValues()
   disposeAllVariables() 
}

Function calls added here will be invoked.

How Viewmodel save the data when the activity gets destroyed and recreated when the device get rotated

ViewModel has its own lifecycle that allows itself to recover its state, and the transient data it holds, during screen rotations.

NOTE: Activity and ViewModel's lifecycle are both ephemeral. Allowing the ViewModel to handle critical or sensitive data during configuration changes IS NOT RECOMMENDED.

Your application should use either shared prefs, secured storage (if necessary), local database or cloud storage when you are expected to handle critical or sensistive data in a specific screen or part of your app.

I recommend that you read the following:

Solution 2:[2]

View Model's Internal Wokring:

View Model:

View Model is a lifecycle awared class, designed to store and manage UI related data. It a main component in MVVM architecture. When a view model is created, it is stored inside activity or fragment manager.

Benefits:

  1. Lifecycle awared
  2. Hold and share UI data
  3. Survives in rotation and retains data

Here we can raise a question that how we can get same instance of view model when new instance of activity is created while rotating screen from portrait to landscape ?

Answer:

To create a viewmodel object, ViewModelProvider class is required.

ViewModelProvider is the utility class which is used to create the instance of viewmodel in the following way.

  1. Create a ViewModelProvider instance
  2. Get the desired viewmodel from the viewmodel provider object

Internally creation of ViewModelProvider required two parameters.

  1. ViewModelStoreOwner: it is an interface.It has just one method which returns the ViewModelStore.

  2. Factory: It is a nested interface in the ViewModelProvider class and is used to manufacture viewmodel objects.

     val viewModelProvider = ViewModelProvider(this)
     val viewModelProvider2 = ViewModelProvider(this,viewModelFactory)
    

If the factory is not passed then the default factory is created. Custom factory can be created for the parameterized viewmodel.

So now we have instance of viewmodel provider, Now let’s get our viewmodel object

 val viewModelProvider = ViewModelProvider(this)
val viewModel = viewModelProvider.get(LoginViewModel::class.java)

As we can see, we simply just called the get(arg) method with the desired viewmodel class reference and our viewmodel object was created.

So all the magic happens in this get method

enter image description here

This method gets the canonical name of the viewmodel class,creates a key by appending DEFAULT_KEY then it calls the another get function which takes the key and viewmodel class reference

enter image description here

This method checks the viewmodel instance in the viewmodel store first.If the viewmodel instance is there in the viewmodelstore then it simply returns that instance .If viewmodel instance is not there then it uses the factory to create the new instance and saves that instance in viewmodel store and then it return the viewmodel instance.

This viewmodel store is linked to ViewModelStoreOwner so our activity/fragment has their own viewmodel store.

It is ViewModelStore which stores the viewmodel and is retained when the rotation occurs and which returns the same viewmodel instance in the new activity instance.

Interview Question : Viewmodel store is linked to activity / fragment and when in the process of rotation current instance is destroyed and new instance is created then how this ViewModelStore object is still the same?

Let’s know about this magic

ViewModelStoreOwner is an interface. ComponentActivity implements this interface.

enter image description here

In above implementation , we can see that in the new activity object when viewmodel store is null then it first checks with the NonConfigurationInstance which returns the previous activity’s viewmodel store.

If activity is being created for the first time then always new viewmodel store objects will be created.

So It is NonConfigurationInstance object which is passed from old destroyed activity to newly created activity when rotations happens.It contains all the non-configuration related information including viewmodel store which contains the viewmodel of old activity object.

Answer is inspired by This Link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joshua de Guzman
Solution 2 Muhammad Zahab Ahmad Khan