-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β Field injection
Devrath edited this page Oct 6, 2023
·
9 revisions
Contents |
---|
Observations |
Output |
Code |
- You can clearly see there are three implementations(
Wheels
,Engine
, andCar
).
// Dagger generates the component from it we can build the component
val mobileComponent = DaggerMobileComponent.builder().build()
// Here we pass the context of the activity since we need the context for field injection for dagger
mobileComponent.inject(this@DaggerConceptsActivity)
// Access the methods of the class from the field injected variable
mobile.runMobile()
Battery constructor is invoked !
Screen constructor is invoked !
Mobile constructor is invoked !
Mobile is running !
Battery.kt
class Battery @Inject constructor() {
init {
printLog("Battery constructor is invoked !")
}
}
Screen.kt
class Screen @Inject constructor(){
init {
printLog("Screen constructor is invoked !")
}
}
Mobile.kt
class Mobile @Inject constructor( var battery: Battery, var screen: Screen){
init { printLog("Mobile constructor is invoked !") }
fun runMobile() { printLog("Mobile is running !") }
}
MobileComponent.kt
@Component
interface MobileComponent {
fun inject(activity: MyActivity)
}
MyActivity.kt class MyActivity : AppCompatActivity() {
private lateinit var binding: ActivityDaggerConceptsBinding
@Inject
lateinit var mobile : Mobile
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDaggerConceptsBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListener()
}
private fun setOnClickListener() {
binding.apply {
// Field Injection
fieldInjectionId.setOnClickListener {
val mobileComponent = MyActivity.builder().build()
mobileComponent.inject(this@MyActivity)
mobile.runMobile()
}
}
}
}