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?
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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With