使用@ViewModelInject将FragmentComponent依赖项注入到viewmodel

时间:2020-10-06 06:22:44

标签: android viewmodel dagger-hilt

我想将我的ViewModel内部片段与FragmentComponent依赖项一起使用,但我认为 @ViewModelInjectActivityComponentApplicationCoinmponent内提供ViewModel,并且无法将我的FragmentComponent依赖项注入ViewModel

class XViewModel @ViewModelInject constructor(
    private val xClass: XClass // this dependency provides in FragmentComponent
) : ViewModel() {

}

当我尝试构建项目时。构建失败,发生KaptException,并且hilt编译器说我无法提供XClassXClassFragmentComonent中提供的内容。 当我将XClass提供者方法移至ActivityComponentApplicationComponent时,KaptException的构建不再失败。

编辑: 我阅读了Hilt生成的代码,我猜对了,Hilt和@ViewModelInjectXViewModel中安装ActivityRetainedComponent模块。我不知道为什么?

@Module
@InstallIn(ActivityRetainedComponent.class)
@OriginatingElement(
    topLevelClass = XViewModel.class
)
public interface XViewModel_HiltModule

1 个答案:

答案 0 :(得分:0)

我找到了答案here。 hilt团队之所以这样做,是因为从fragment组件注入东西可能会在配置更改中泄漏Fragment实例。 ActivityRetainedComponent存在于配置更改中,因此它是在第一个onCreate和最后一个onDestroy上创建的