简体   繁体   English

如何使用Dagger2在Android中注入LifecycleOwner?

[英]How to inject a LifecycleOwner in Android using Dagger2?

I happen to have an Android lifecycle aware component with the following interface: 我碰巧有一个具有以下界面的Android生命周期感知组件:

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

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

    ...
}

All Dagger specific components and modules are configured correctly and have been working great so far. 所有Dagger特定组件和模块均已正确配置,并且到目前为止运行良好。

In each activity when I need to use the component I do the following: 在每个活动中,当我需要使用组件时,请执行以下操作:

class MyActivity: AppCompatActivity() {
    @Inject
    lateinit var component: MyLifecycleAwareComponent

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

Now I want to get rid of bindLifecycleOwner and denote my component like this: 现在,我想摆脱bindLifecycleOwner并像这样表示我的组件:

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

And provide the lifecycleOwner within the scope of individual activities (which implement the interface by extending AppCompatActivity ). 并在各个活动(通过扩展AppCompatActivity实现接口)的范围内提供lifecycleOwner

Is there any way to do it with Dagger? 有什么办法可以用匕首做到吗?

You may bind your Activity to LifecycleOwner from your ActivityModule: 您可以从ActivityModule将Activity绑定到LifecycleOwner:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM