我试图理解为什么是 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/