简体   繁体   English

ViewModelProvider 构造函数有什么区别

[英]what is the difference between ViewModelProvider constructors

I am learning about ViewModel and I was wondering is there any difference between theses methods to get a ViewModelProvider instance?我正在学习 ViewModel,我想知道这些获取ViewModelProvider实例的方法之间有什么区别吗?

method A:方法一:

ViewModelProvider viewModelProvider = new ViewModelProvider(getViewModelStore(),
                ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()));
mViewModel = viewModelProvider.get(NoteActivityViewModel.class);

method B:方法B:

mViewModel = new ViewModelProvider(this).get(NoteActivityViewModel.class);

As per the ViewModelProvider(ViewmodelStoreOwner) documentation :根据ViewModelProvider(ViewmodelStoreOwner)文档

This method will use the default factory if the owner implements HasDefaultViewModelProviderFactory .如果所有者实现HasDefaultViewModelProviderFactory ,此方法将使用默认工厂 Otherwise, a ViewModelProvider.NewInstanceFactory will be used.否则,将使用ViewModelProvider.NewInstanceFactory

And as per the Lifecycle 2.2.0 release notes (which was when that constructor was added):根据Lifecycle 2.2.0 发行说明(添加该构造函数时):

You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality when using Fragment 1.2.0 .您可以将FragmentFragmentActivity传递给新的ViewModelProvider(ViewModelStoreOwner)构造函数,以在使用Fragment 1.2.0时实现相同的功能。

And the Fragment 1.2.0 release notes state that: Fragment 1.2.0 发行说明state 指出:

SavedStateViewModelFactory is now the default factory used when using by viewModels() , by activityViewModels() , the ViewModelProvider constructor, or ViewModelProviders.of() with a Fragment. SavedStateViewModelFactory现在是by viewModels()by activityViewModels()ViewModelProvider构造函数或ViewModelProviders.of()与 Fragment 使用时使用的默认工厂。

So new ViewModelProvider(this) uses SavedStateViewModelFactory , which provides everything that AndroidViewModelFactory provides in addition to support for the Saved State module for ViewModel .所以new ViewModelProvider(this)使用SavedStateViewModelFactory ,它提供了AndroidViewModelFactory提供的一切,除了支持ViewModel 的 Saved State 模块

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.使用 Fragment 1.2.0 或更高版本时,没有理由将ViewModelProvider与标准工厂之一一起使用 - 只有当您拥有自己的自定义工厂时,该构造函数才有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM