为什么要对视图模型使用viewmodelproviders? [英] Why should I use viewmodelproviders for viewmodels?

查看:484
本文介绍了为什么要对视图模型使用viewmodelproviders?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我应该对viewmodel使用viewmodelproviders?

Why should I use viewmodelproviders for viewmodels?

为什么我不能将自定义单例注释添加到我的视图模型,然后将此视图模型注入片段类?

Why I just can't add custom singleton annotation to my viewmodel, and then inject this viewmodel to fragment class?

像这样:

@MainScope
class MainViewModel @Inject constructor(): ViewModel()

然后:

open class BaseFragment<T: ViewModel>: DaggerFragment() {
@Inject
protected lateinit var viewModel: T

这两种情况都与屏幕旋转无关.

Both cases are independent of screen rotation.

单例注释案例是否有任何弊端? 我只看到优点,使用这种方法,无需复制/粘贴大量代码.

Is there any drawbacks of singleton annotation case? I see only advantages, with this approach I don't need to copy/paste tons of code.

推荐答案

为什么要对viewmodel使用viewmodelproviders?

Why should I use viewmodelproviders for viewmodels?

要获取viewModel.onCleared()ComponentActivity正确的时间正确调用的回调.

To get viewModel.onCleared() callback called properly at the right time by the ComponentActivity.

(并确保为给定的ViewModelStoreOwner只创建一次).

(and to ensure it's created only once for the given ViewModelStoreOwner).

为什么我不能将自定义单例注释添加到我的视图模型,然后将此视图模型注入片段类?

Why I just can't add custom singleton annotation to my viewmodel, and then inject this viewmodel to fragment class?

因为您不会在ComponentActivity的正确时间正确调用viewModel.onCleared()回调.

Because you won't get viewModel.onCleared() callback called properly at the right time by the ComponentActivity.

单例注释案例是否有任何缺点?我只看到优势,

Is there any drawbacks of singleton annotation case? I see only advantages,

您不会得到viewModel.onCleared().

如果您有一个singleton变体,则ViewModel不会随其封闭的Finishing Activity一起消失,甚至在向后导航时也可以保持活动状态(这可能不是故意的).

Also if you have a singleton variant, then the ViewModel won't die along with its enclosing finishing Activity, and stay alive even on back navigation (which is probably not intended).

使用这种方法,我不需要复制/粘贴大量代码.

with this approach I don't need to copy/paste tons of code.

您正在使用Kotlin.使用扩展功能.

You're using Kotlin. Use extension functions.

这篇关于为什么要对视图模型使用viewmodelproviders?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆