How does an activity manage configuration changes while ensuring the ViewModel instance remains…
<p><em>Question: </em>How does ViewModelProviders know when there is a configuration change vs user explicitly creating a new activity or onDesctory() called?</p>
<p><strong>Answer:</strong> </p>
<p>The provided code within ComponentActivity monitors lifecycle changes. If onDestroy() is invoked without configuration changes, the ViewModel store is cleared. On the other hand, if onDestroy() is called with configuration changes, the ViewModel instance perseveres.</p>
<pre>
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});</pre>
<p><strong>Explanation</strong></p>
<ol>
<li><strong>Adding a Lifecycle Observer</strong>: It attaches an observer to the current screen’s lifecycle. This observer watches for changes in the lifecycle of the screen.</li>
<li><strong>Detecting ON_DESTROY Event</strong>: When the screen is about to be destroyed, the code checks if the event is the “<strong>ON_DESTROY</strong>” event. This event happens when the screen is being removed.</li>
<li><strong>Clearing ViewModelStore</strong>: If the screen is truly being destroyed (not just changing configuration), the code clears the ViewModelStore. ViewModelStore is where the app’s data is stored during the screen’s lifetime otherwise <strong>ViewModel</strong> instance remains alive</li>
</ol>
<p>This is a prime example of disposing of unnecessary objects when they are no longer required.</p>
<p><a href="https://taimurtanveer.medium.com/how-does-an-activity-manage-configuration-changes-while-ensuring-the-viewmodel-instance-remains-8fe3af06da3b">Visit Now</a></p>