-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β Constructor injection
Devrath edited this page Oct 5, 2023
·
9 revisions
Contents |
|---|
| Observations |
| Output |
| Code |
- You can clearly see there are three implementations(
Wheels,Engine, andCar). - The
Engineand theWheelsare passed in the constructor of theCarclass. - All the three implementations are annotated with
@Injectannotation. This notifies the dagger that these classes are available for the dagger to build objects. - Thus, The
Wheelsand theEngineare injected in the constructor of theCarclass. - The
CarComponentclass is an interface annotated with@Component. - The component class returns the
Carobject that gets created by dagger. - Now a class is generated called
DaggerCarComponentwhich will implement theCarComponentinterface and return aCarobject. During thecarobject creation time if any further dependencies are there that need to be created, dagger takes care of it.
// Create function invokes a builder pattern & GetCar function gets the object
val car: Car = DaggerCarComponent.create().getCar()
// With the help of the reference, one could access all methods of car object
car.start()
Wheels constructor is invoked !
Engine constructor is invoked !
Car constructor is invoked !
Car is DrivingContents |
|---|
| Implementations |
| Components |
Engine.kt
class Engine @Inject constructor() {
init {
printLog("Engine constructor is invoked !")
}
}Wheels.kt
class Wheels @Inject constructor() {
init {
PrintUtils.printLog("Wheels constructor is invoked !")
}
}Car.kt
class Car @Inject constructor(
var wheels: Wheels,
var engine: Engine
) {
init {
printLog("Car constructor is invoked !")
}
fun start() {
printLog("Car is Driving")
}
}CarComponent
@Component
interface CarComponent {
fun getCar() : Car
}MyActivity.kt
class MyActivity : AppCompatActivity() {
private lateinit var binding: ActivityDaggerConceptsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDaggerConceptsBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListener()
}
private fun setOnClickListener() {
binding.apply {
// Constructor Injection
constructorInjectionId.setOnClickListener {
val car: Car = DaggerCarComponent.create().getCar()
car.start()
}
}
}
}