我碰巧有一个具有以下界面的Android生命周期感知组件:
class MyLifecycleAwareComponent @Inject constructor(
private val: DependencyOne,
private val: DependencyTwo
) {
fun bindToLifecycleOwner(lifecycleOwner: LifecycleOwner) {
...
}
...
}
所有Dagger特定组件和模块都已正确配置,并且到目前为止运行良好。
在每个活动中,当我需要使用组件时,请执行以下操作:
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
) {
...
}
并在各个活动的范围内提供lifecycleOwner
(这些活动通过扩展AppCompatActivity
来实现该接口)。
有什么办法可以用匕首做到吗?
答案 0 :(得分:1)
您可以将Activity从ActivityModule绑定到LifecycleOwner:
@Module
abstract class ActivityModule {
...
@Binds
@ActivityScope
abstract fun bindLifecycleOwner(activity: AppCompatActivity): LifecycleOwner
...
}