我个人并没有发现什么大的区别,但也许这两者之间隐藏着什么?
源代码如下
package org.koin.androidx.viewmodel.ext.android
/**
* Fragment extension to help for Viewmodel
*
* @author Arnaud Giuliani
*/
inline fun <reified T : ViewModel> Fragment.sharedViewModel(
qualifier: Qualifier? = null,
noinline owner: ViewModelStoreOwnerProducer = { requireActivity() },
noinline parameters: ParametersDefinition? = null,
): Lazy<T> {
return viewModel(qualifier, owner, parameters)
}
package androidx.fragment.app
/**
* Returns a property delegate to access parent activity's [ViewModel],
* if [factoryProducer] is specified then [ViewModelProvider.Factory]
* returned by it will be used to create [ViewModel] first time. Otherwise, the activity's
* [androidx.activity.ComponentActivity.getDefaultViewModelProviderFactory](default factory)
* will be used.
*
* ```
* class MyFragment : Fragment() {
* val viewmodel: MyViewModel by activityViewModels()
* }
* ```
*
* This property can be accessed only after this Fragment is attached i.e., after
* [Fragment.onAttach()], and access prior to that will result in IllegalArgumentException.
*/
@MainThread
public inline fun <reified VM : ViewModel> Fragment.activityViewModels(
noinline extrasProducer: (() -> CreationExtras)? = null,
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> = createViewModelLazy(
VM::class, { requireActivity().viewModelStore },
{ extrasProducer?.invoke() ?: requireActivity().defaultViewModelCreationExtras },
factoryProducer ?: { requireActivity().defaultViewModelProviderFactory }
)
1条答案
按热度按时间ujv3wf0j1#
它们最初被称为
sharedViewModel
,但AndroidX ViewModel的API已经改变,并且能够创建更具体的“共享”ViewModel。活动范围、导航图范围等。sharedViewModel
是一个令人困惑的名字。它实际上是Activity作用域的ViewModel,但不能通过方法名读取。ViewModel在单个Activity应用程序中意外地为单例。Koin可能已经跟随了这个API的变化。