I am learning about ViewModel and I was wondering is there any difference between theses methods to get a ViewModelProvider
instance?
method A:
ViewModelProvider viewModelProvider = new ViewModelProvider(getViewModelStore(),
ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()));
mViewModel = viewModelProvider.get(NoteActivityViewModel.class);
method B:
mViewModel = new ViewModelProvider(this).get(NoteActivityViewModel.class);
As per the ViewModelProvider(ViewmodelStoreOwner)
documentation:
This method will use the default factory if the owner implements
HasDefaultViewModelProviderFactory
. Otherwise, aViewModelProvider.NewInstanceFactory
will be used.
And as per the Lifecycle 2.2.0 release notes (which was when that constructor was added):
You can pass a
Fragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality when using Fragment 1.2.0.
And the Fragment 1.2.0 release notes state that:
SavedStateViewModelFactory
is now the default factory used when usingby viewModels()
,by activityViewModels()
, theViewModelProvider
constructor, orViewModelProviders.of()
with a Fragment.
So new ViewModelProvider(this)
uses SavedStateViewModelFactory
, which provides everything that AndroidViewModelFactory
provides in addition to support for the Saved State module for ViewModel.
There would be no reason to use the ViewModelProvider
with one of the standard factories when using Fragment 1.2.0 or higher - that constructor would only be useful if you have your own custom factory.