Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 752
Archibald Avatar asked Feb 03 '26 17:02

Archibald


1 Answers

You may bind your Activity to LifecycleOwner from your ActivityModule:

@Module
abstract class ActivityModule {
    ...
    @Binds
    @ActivityScope
    abstract fun bindLifecycleOwner(activity: AppCompatActivity): LifecycleOwner
    ...
}
like image 64
Samuel Eminet Avatar answered Feb 06 '26 06:02

Samuel Eminet