在
Jetpack
组件中,我们一般会用到ViewModel
,那么我们来说下它的几种创建模式和应用场景
1.第一种方式
val viewModel by lazy {
ViewModelProvider(this,ViewModelProvider.NewInstanceFactory()).get(modelClass)
}
一般在
Activity
中使用,它只会被创建一次
2.第二种方式
val viewModel by lazy {
ViewModelProvider(requireActivity(),ViewModelProvider.NewInstanceFactory()).get(modelClass)
}
一般被用于
Fragment
,它也只有一个实例,被用于Fragment
的数据共享
3.第三种方式
val viewModel by lazy {
ViewModelProvider.NewInstanceFactory().create(modelClass)
}
一般被用于
Fragment
,但是它会随着Fragment
的重新创建,也会随着Fragment
销毁而销毁,一般配合着ViewPager
里面的Fragment
使用。
4.第四种方式
private val vm:PlayerViewModel by viewModels()
private val vm:PlayerViewModel by activityViewModels()
第一种,viewModelStore是fragment本身;
第二种,viewModelStore是Activity,这个其实是获取Activity的ViewModel;
@MainThread
inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
@MainThread
fun <VM : ViewModel> Fragment.createViewModelLazy(
viewModelClass: KClass<VM>,
storeProducer: () -> ViewModelStore,
factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
val factoryPromise = factoryProducer ?: {
defaultViewModelProviderFactory
}
return ViewModelLazy(viewModelClass, storeProducer, factoryPromise)
}
--------------------------------------------------------------------------------------------------------
@MainThread
inline fun <reified VM : ViewModel> Fragment.activityViewModels(
noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { requireActivity().viewModelStore },
factoryProducer ?: { requireActivity().defaultViewModelProviderFactory })