Pranay
Pranay

Reputation: 304

How ViewModel retains data?

How can viewModel retains data due to configuration changes but not when we try to re instantiate the activity.

ViewModel objects are scoped to the Lifecycle passed to the ViewModelProvider when getting the ViewModel. The ViewModel remains in memory until the Lifecycle it's scoped to goes away permanently

 viewModel = ViewModelProviders.of(this)[MainActivityViewModel::class.java]

Here this is the lifecycle owner MainActivity.
Before rotation/ config change: enter image description here After rotation/ config change: enter image description here

We can clearly see here that instance of activity (owner) and lifecycle are changing after rotation. So why its saving the data only in configuration changes. Meanwhile when i tried creating a new instance of same activity manually to re create this scenario the view model is not retaining the data.

What are the deciding parameters for view model to retain the data or not.
And why viewModel retains the data only for config changes and not for something like new instance of same activity.

Upvotes: 1

Views: 1204

Answers (1)

Radhika Tiwari
Radhika Tiwari

Reputation: 54

There is an observer set on the lifecycle of activity/ fragment inside ComponentActivity constructor.

getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source,
                    @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    // Clear out the available context
                    mContextAwareHelper.clearAvailableContext();
                    // And clear the ViewModelStore
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });

ComponentActivity is the parent class of Fragment and AppCompactActivity.
It'll be triggered everytime a lifecycle call back is made and if its onDestroy() callback and if its not a configuration change only then it will clear the viewModelStore.

           if (!isChangingConfigurations()) {
             getViewModelStore().clear();
           }

so the deciding parameter is isChangingConfigurations()

Upvotes: 3

Related Questions