Search code examples
androidkotlindagger-2android-lifecycle

How to inject a LifecycleOwner in Android using Dagger2?


I happen to have an Android lifecycle aware component with the following interface:

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.

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:

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).

Is there any way to do it with Dagger?


Solution

  • You may bind your Activity to LifecycleOwner from your ActivityModule:

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