android - 刀柄 : Why is ActivityRetainedScoped vs ViewModelScoped

标签 android dagger-2 dagger-hilt

我试图理解为什么是 ActivityRetainedScoped在 Hilt 中为 DI 引入。在我看来,范围与 ViewModelScoped 相同。应该做。我的印象是作用域是这样工作的:AppScope (singleton) > ViewModelScope > ActivityScope > ViewScope > ...但是this graphic有点暗示 ViewModel 和 Activity 范围是...... sibling ?
根据文档:

"ActivityRetainedComponent lives across configuration changes, so it is created at the first Activity#onCreate() and destroyed at the last Activity#onDestroy()."


那么, View 模型也是如此,不是吗?
我很确定 View 模型可以在配置更改中幸存下来(如果首先拥有它们,那就是重点)
什么是ActivityRetainedScoped ?它与 VM 范围有何不同?为什么谷歌喜欢把概念上应该简单的事情复杂化
https://developer.android.com/training/dependency-injection/hilt-android

最佳答案

好吧,即使 ActivityRetainedScope 和 ViewModelScope 是 sibling ,人们可能会认为这使它们相同,但实际上并非如此。

Well, so does the view model, no? I'm pretty sure view models survive config changes (that's the whole point if having them in the first place)


是的,但实际上没有。 Viewmodel 确实可以在配置更改中保留下来,但仅限于其范围内的生命周期所有者。因此,让我们考虑以下场景:
你有两个依赖,一个是 ActivtyRetainedScoped另一个是 viewmodelscoped .
当您现在在 viewmodel 中注入(inject) viewmodeldependency 并且 viewmodel 的生命周期所有者是一个 Activity 时,那么您是对的,ActivtyRetainedScope 和 ViewmodelScope 都不会有任何区别。
但是现在让我们假设生命周期所有者是一个 fragment ,在这种情况下,当您导航出 fragment 时,viewmodelscoped 依赖项将“死亡”,并且 activtyretainedscope 依赖项将比 viewmodelscoped 依赖项生命周期长。
我希望我能解释它们之间的区别。当英语不是您的母语时,那些“范围”等有点难。另外,如果这是正确答案,我不是 100%

关于android - 刀柄 : Why is ActivityRetainedScoped vs ViewModelScoped,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67765298/

相关文章:

Android 库、Kotlin 和 Dagger2

android - Hilt 无法将 ContextImpl 转换为 Application

android - 如何在 Dagger Hilt 中获得 MVP?

android - Dagger2 一个模块用于两个不同的范围

android - 使用 Hilt 将 ViewModel 注入(inject) ViewModel

android - 安卓工作室 : ExecutionException : (integer) -1 is less than minimum integer 0

java - Android 媒体播放器错误 1,-1002

android - 将服务器类添加到 android.jar

android - [错误 : Failed to find 'ANDROID_HOME' environment variable. 尝试手动设置

android - Dagger2 @Binds 方法的参数类型必须可分配给具有接口(interface)和实现的返回类型