Search code examples
android-lifecycleandroid-jetpackandroid-viewmodel

How should I interpret the Android Developers ViewModel lifecycle diagram?


The following diagram appears in the Android Jetpack ViewModel Overview: ViewModel lifecycle diagram

Why does the upper onDestroy graphic in the middle column have a pointy end and not terminate the ViewModel Scope while the other onDestroy graphic has a square end and terminate the ViewModel Scope?


Solution

  • I was able to get in touch with the creator of the diagram, Jose Alcérreca, who told me "the second onDestroy doesn't have an arrow is because it's the end of the activity's lifecycle (triggered by finish() not a recreation)."

    I was also pointed to the source code for ComponentActivity, which shows the observer for ON_DESTROY:

        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();     // ***
                    }
                }
            }
        });
    

    As the starred lines show, the clear() method is called for the ViewModelStore only if the call to onDestroy() is not due to a configuration change.