gpt4 book ai didi

android - 为什么我应该为 View 模型使用 viewmodelproviders?

转载 作者:行者123 更新时间:2023-12-03 10:12:43 28 4
gpt4 key购买 nike

为什么我应该为 View 模型使用 viewmodelproviders?

为什么我不能将自定义单例注释添加到我的 View 模型中,然后将此 View 模型注入(inject) fragment 类?

像这样:

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

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

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

单例注释案例有什么缺点吗?
我只看到优点,使用这种方法我不需要复制/粘贴大量代码。

最佳答案

Why should I use viewmodelproviders for viewmodels?



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

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

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



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

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



你没有得到 viewModel.onCleared() .

此外,如果您有一个单例变体,那么 ViewModel 不会随着其封闭的完成 Activity 而死,并且即使在后退导航(这可能不是故意的)上也能保持活力。

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



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

关于android - 为什么我应该为 View 模型使用 viewmodelproviders?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58189456/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com