android ViewModelProviders已过时,应替换哪些内容?

xqkwcwgp  于 2023-11-06  发布在  Android
关注(0)|答案(2)|浏览(195)

我使用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]
}

你能解释一下为什么它过时了吗

wsewodh2

wsewodh21#

根据文件:
使用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 }
zpqajqem

zpqajqem2#

如果您的ViewModel具有一些依赖项,则可以使用delegate ...

protected val viewModel by activityViewModels<MainViewModel> {
    ViewModelFactory(ServicesRepo())
}

相关问题