我碰巧有一个具有以下界面的Android生命周期感知组件:

class MyLifecycleAwareComponent @Inject constructor(
    private val: DependencyOne,
    private val: DependencyTwo
) {

    fun bindToLifecycleOwner(lifecycleOwner: LifecycleOwner) {
        ...
    }

    ...
}

所有Dagger特定组件和模块均已正确配置,并且到目前为止运行良好。

在每个 Activity 中,当我需要使用组件时,请执行以下操作:
class MyActivity: AppCompatActivity() {
    @Inject
    lateinit var component: MyLifecycleAwareComponent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        component.bindToLifecycleOwner(this)
        ...
    }
}

现在,我想摆脱bindLifecycleOwner并像这样表示我的组件:
class MyLifecycleAwareComponent @Inject constructor(
    private val: DependencyOne,
    private val: DependencyTwo,
    private val: LifecycleOwner
) {
    ...
}

并在各个 Activity 的范围内提供lifecycleOwner(通过扩展AppCompatActivity来实现接口(interface))。

有什么办法可以用 Dagger 做到吗?

最佳答案

您可以从ActivityModule将Activity绑定(bind)到LifecycleOwner:

@Module
abstract class ActivityModule {
    ...
    @Binds
    @ActivityScope
    abstract fun bindLifecycleOwner(activity: AppCompatActivity): LifecycleOwner
    ...
}

关于android - 如何使用Dagger2在Android中注入(inject)LifecycleOwner?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52689803/

10-08 23:16