How does ViewModelProviders know when there is a configuration change VS user explicitly creates a new activity?

public class MainActivity extends Activity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         
         MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
         
         viewModel.getUsers().observer(this, new Observer() {
            @Override
             public void onChanged(@Nullable User data) {
                 // update the ui.
             }
         });
        
     }
}

For example, if I create this activity above and rotate the screen, I am assuming MyViewModel will be retained. But when I finish the activity and create a new one, I should see a brand new activity with new MyViewModel .

From my understanding, configuration change will initiate the same callbacks(onPause,onStop,onDestroy then onCreate,onStart,onResume), which seem to be the same as user finishes the activity and manually create it again.

So how does ViewModelProviders determine which is which?

Any feedbacks are appreciated!


Solution 1:

You can see in source of ComponentActivity that it checks isChangingConfigurations() upon destruction:

// listener registered in 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();
            }
        }
    }
});