使用@ViewModelInject 将 FragmentComponent 依赖项注入 viewmodel
Inject FragmentComponent dependencies to viewmodel with @ViewModelInject
我想使用具有 FragmentComponent
依赖项的 ViewModel
内部片段,但我认为
@ViewModelInject
在 ActivityComponent
或 ApplicationCoinmponent
中提供 ViewModel 并且无法将我的 FragmentComponent
依赖项注入 ViewModel
class XViewModel @ViewModelInject constructor(
private val xClass: XClass // this dependency provides in FragmentComponent
) : ViewModel() {
}
当我尝试构建项目时。构建失败 KaptException
,刀柄编译器说我无法提供 XClass
。 XClass
在 FragmentComonent
中提供。
当我将 XClass
提供程序方法移动到 ActivityComponent
或 ApplicationComponent
时,构建不再因 KaptException
.
而失败
编辑:
我阅读了 Hilt 生成的代码,我的猜测是正确的,Hilt 和 @ViewModelInject
在 ActivityRetainedComponent
中安装 XViewModel
模块。我不知道为什么?
@Module
@InstallIn(ActivityRetainedComponent.class)
@OriginatingElement(
topLevelClass = XViewModel.class
)
public interface XViewModel_HiltModule
我找到了答案here。 hilt 团队这样做是因为从片段组件注入东西可能会跨配置更改泄漏片段实例。
ActivityRetainedComponent
存在于配置更改中,因此它在第一个 onCreate 和最后一个 onDestroy 时创建
我想使用具有 FragmentComponent
依赖项的 ViewModel
内部片段,但我认为
@ViewModelInject
在 ActivityComponent
或 ApplicationCoinmponent
中提供 ViewModel 并且无法将我的 FragmentComponent
依赖项注入 ViewModel
class XViewModel @ViewModelInject constructor(
private val xClass: XClass // this dependency provides in FragmentComponent
) : ViewModel() {
}
当我尝试构建项目时。构建失败 KaptException
,刀柄编译器说我无法提供 XClass
。 XClass
在 FragmentComonent
中提供。
当我将 XClass
提供程序方法移动到 ActivityComponent
或 ApplicationComponent
时,构建不再因 KaptException
.
编辑:
我阅读了 Hilt 生成的代码,我的猜测是正确的,Hilt 和 @ViewModelInject
在 ActivityRetainedComponent
中安装 XViewModel
模块。我不知道为什么?
@Module
@InstallIn(ActivityRetainedComponent.class)
@OriginatingElement(
topLevelClass = XViewModel.class
)
public interface XViewModel_HiltModule
我找到了答案here。 hilt 团队这样做是因为从片段组件注入东西可能会跨配置更改泄漏片段实例。
ActivityRetainedComponent
存在于配置更改中,因此它在第一个 onCreate 和最后一个 onDestroy 时创建