sharedViewModel. vs activityViewModel



我个人没有发现有什么大的区别,但也许这两者之间隐藏着什么?

源代码在

下面
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 }
)

它们最初被称为sharedViewModel,但AndroidX ViewModel的API已经改变,更具体的"共享"。可以创建ViewModel。活动范围、导航图范围等

sharedViewModel是混淆的名称。它实际上是活动范围的ViewModel,但它不是通过方法名称可读的。ViewModel会在单个Activity应用中意外地成为单例。

Koin可能已经跟随这个API更改了。

相关内容

  • 没有找到相关文章

最新更新