英文:
what is the difference between ViewModelProvider constructors
问题
方法A:
ViewModelProvider viewModelProvider = new ViewModelProvider(getViewModelStore(),
ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()));
mViewModel = viewModelProvider.get(NoteActivityViewModel.class);
方法B:
mViewModel = new ViewModelProvider(this).get(NoteActivityViewModel.class);
英文:
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);
答案1
得分: 0
根据 ViewModelProvider(ViewmodelStoreOwner)
文档:
> 如果拥有者实现了 HasDefaultViewModelProviderFactory
,此方法将使用默认工厂。否则,将使用 ViewModelProvider.NewInstanceFactory
。
根据 Lifecycle 2.2.0 发布说明(当时添加了该构造函数):
> 当使用 Fragment 1.2.0 时,您可以将 Fragment
或 FragmentActivity
传递给新的 ViewModelProvider(ViewModelStoreOwner)
构造函数以实现相同的功能。
而 Fragment 1.2.0 发布说明 指出:
> 当使用 by viewModels()
、by activityViewModels()
、ViewModelProvider
构造函数或带有 Fragment 的 ViewModelProviders.of()
时,SavedStateViewModelFactory
现在是默认工厂。
因此,new ViewModelProvider(this)
使用 SavedStateViewModelFactory
,它提供了 AndroidViewModelFactory
提供的一切,还支持 ViewModel 的保存状态模块。
如果您使用 Fragment 1.2.0 或更高版本,没有理由使用标准工厂之一与 ViewModelProvider
一起 - 该构造函数仅在您拥有自定义工厂时才有用。
英文:
As per the ViewModelProvider(ViewmodelStoreOwner)
documentation:
> This method will use the default factory if the owner implements HasDefaultViewModelProviderFactory
. Otherwise, a ViewModelProvider.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
or FragmentActivity
to the new ViewModelProvider(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 using by viewModels()
, by activityViewModels()
, the ViewModelProvider
constructor, or ViewModelProviders.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论