Skip to content

Bind to the Activity

Valery edited this page Jan 8, 2019 · 6 revisions

Bind the component to the Activity is the same as bind the component to the Application class.

Firstly, implement the IHasComponent interface in your Activity class.

The method getComponent should return the dagger component.

Also, you can override the getComponentKey method, so the every new instance of the Activity class will work with its own component, but not with a "global" component. If it's okay that the activities will work with the same Dagger component, don't override the getComponentKey method. Otherwise, override the getComponentKey method and make it returns a unique key for the every activity.

class DetailsActivity : AppCompatActivity(), IHasComponent<DetailsComponent> {

    companion object {
        private const val EXTRA_ID = "extra_id"
        fun newIntent(context: Context, id: Int): Intent =
            Intent(context, DetailsActivity::class.java)
                .putExtra(EXTRA_ID, id)
    }

    private val extraId by lazy { intent.getIntExtra(EXTRA_ID, -1) }
   
    //...code...

    override fun getComponent(): DetailsComponent = DaggerDetailsComponent.create()

    override fun getComponentKey(): String = "DetailsActivity_$extraId"
}

After this, every activity will have its own component.

In the end, bind the component to the owner by calling the bindComponent<ComponentClass>(this) method.

class DetailsActivity : AppCompatActivity(), IHasComponent<DetailsComponent> {

    //...code...

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        XInjectionManager
            .bindComponent<DetailsComponent>(this)
            .inject(this)
    }
   
    //...code...
}

Clone this wiki locally