Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How ViewModel is persisted on configuration change

Looking at the ViewModel documentation, it says:

In other words, this means that a ViewModel will not be destroyed if its owner is destroyed for a configuration change (e.g. rotation). The new instance of the owner will just re-connected to the existing ViewModel.

How is the ViewModel not destroyed if the activity referencing it is destroyed? and how is it reconnected once we create a new activity?

like image 210
TareK Khoury Avatar asked Jan 08 '18 07:01

TareK Khoury


People also ask

How does ViewModel survive change configuration?

Using ViewModel to Store UI State. The Android team introduced ViewModel and LiveData classes to help save state during configuration changes. A ViewModel stores and manages UI-related data in a lifecycle-conscious manner. Simply put, it allows data to survive configuration changes.

How does a ViewModel retain itself?

ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. FYI: You can use ViewModel to preserve UI state only during a configuration change, nothing else as explained perfectly in this official doc.

What is the lifetime of ViewModel?

According to docs, viewmodel remains in memory until activity finish or fragment deattach. They also give example with figure showing viewmodel survive in configuration change but destroy after finish() method call. But while configuration changes there is ondestroy() method.

How does a ViewModel work internally?

ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way.It is the main component in the MVVM architecture. ViewModel can be created with activity context or fragment context. When a ViewModel object is created, it is stored inside Activity OR FragmentManager.


2 Answers

The answer is if you use ViewModelProviders.of(this).get(YourViewModel.class) to create ViewModel, the library will cache the ViewModel for you. If you create your ViewModel use "new YourViewModel()", the ViewModel will recreate each time when the activity configuration change. In the ViewModelProviders, it will crate a HolderFragment to add to your activity or your fragment, it's invisible, when the configuration changed, activity destroyed, but the cache is still alive, so next time activity create, the ViewModel will reconnect to it.

like image 181
yu wang Avatar answered Sep 21 '22 15:09

yu wang


Behind the scenes a retained fragment is used. A retained fragment has its state retained across Activity re-creation (such as from a configuration change).

See "Architecture Components Introduction" talk from Google IO 2017, where Yigit Boyar talks about ViewModel.

like image 28
azizbekian Avatar answered Sep 23 '22 15:09

azizbekian