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