ViewModelProviders已过时,应替换什么?

时间:2019-11-09 18:29:54

标签: android kotlin

我使用ViewModelProviders。但是今天,在更新库之后,有30条消息。据我了解,ViewModelProviders不再可用,您需要替换它,我查看了developer.google,但不知道要替换什么?我的代码:

inline fun <reified T : ViewModel> FragmentActivity.injectViewModel(factory: ViewModelProvider.Factory): T {
    return ViewModelProviders.of(this, factory)[T::class.java]
}

inline fun <reified T : ViewModel> Fragment.injectViewModel(factory: ViewModelProvider.Factory): T {
    return ViewModelProviders.of(this, factory)[T::class.java]
}

您能解释一下为什么过时吗?

1 个答案:

答案 0 :(得分:3)

根据the documentation

  

使用by viewModels() Kotlin属性委托或ViewModelProvider.ViewModelProvider(ViewModelStoreOwner, Factory),传入片段和工厂。

因此,您可以将扩展程序替换为:

inline fun <reified T : ViewModel> FragmentActivity.injectViewModel(factory:  ViewModelProvider.Factory): T {
    return ViewModelProvider(this, factory)[T::class.java]
}

inline fun <reified T : ViewModel> Fragment.injectViewModel(factory: ViewModelProvider.Factory): T {
    return ViewModelProvider(this, factory)[T::class.java]
}

并且,根据错误消息,您可以改为使用fragment-ktxactivity-ktx依赖项中的Kotlin属性扩展,并完全删除扩展方法。

即片段的by viewModelsby activityViewModels

// Retrieve the ViewModel associated with this Fragment
val viewModel: MyVewModel by viewModels { myFactory }

// Retrieve the ViewModel associated with the activity
val activityViewModel: MyVewModel by activityViewModels { myFactory }

或者,如果您是从Activity本身访问ViewModel,则可以使用其by viewModels

// In an Activity, you can retrieve a ViewModel scoped to the Activity
// by using viewModels
val viewModel: MyVewModel by viewModels { myFactory }