-
Notifications
You must be signed in to change notification settings - Fork 8
Bind to the Activity
Valery edited this page Aug 30, 2018
·
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 Application class.
The method createComponent should return the dagger component.
But now, you can override the getComponentKey method, because you app can contain several instances of the activity class and every activity will work with the same component.
If it is okay for your case, don't override the getComponentKey method.
But if it is not, override the getComponentKey method and make it returns a unique key for the every activity.
class DetailsActivity : AppCompatActivity(), IHasComponent {
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 createComponent(): DetailsComponent =
DaggerDetailsComponent.builder().build()
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)
class DetailsActivity : AppCompatActivity(), IHasComponent {
//...code...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
XInjectionManager.instance
.bindComponent<DetailsComponent>(this)
.inject(this)
}
//...code...
}