【问题标题】:Inject FragmentComponent dependencies to viewmodel with @ViewModelInject使用 @ViewModelInject 将 FragmentComponent 依赖项注入视图模型
【发布时间】:2020-10-06 18:27:34
【问题描述】:

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

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

}

当我尝试构建项目时。使用KaptException 构建失败,并且刀柄编译器说我无法提供XClass。其中XClassFragmentComonent 中提供。 当我将XClass 提供程序方法移动到ActivityComponentApplicationComponent 时,使用KaptException 构建不再失败。

编辑: 我阅读了 Hilt 生成的代码,我的猜测是正确的,Hilt 和@ViewModelInjectActivityRetainedComponent 中安装XViewModel 模块。我不知道为什么?

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

【问题讨论】:

  • 请将错误日志添加到问题中
  • 在您有XClass 的提供者的位置添加类。并且您的问题的标题和描述不包含相同的问题。请说清楚
  • @AliSh 刀柄错误:如果没有 @Inject 或提供程序方法,则无法提供 XClass。但是XClassFragmentComponent 中提供,当我将XClass 提供程序移动到ActivityComponentApplicationComponent 时,一切正常。

标签: android viewmodel dagger-hilt


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 2015-07-16
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多