-
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
Engine
and theWheels
are passed in the constructor of theCar
class. - All the three implementations are annotated with
@Inject
annotation. This notifies the dagger that these classes are available for the dagger to build objects. - Thus, The
Wheels
and theEngine
are injected in the constructor of theCar
class. - The
CarComponent
class is an interface annotated with@Component
. - The component class returns the
Car
object that gets created by dagger. - Now a class is generated called
DaggerCarComponent
which will implement theCarComponent
interface and return aCar
object. During thecar
object 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 Driving
Contents |
---|
Implementations |
Components |
Activity |
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()
}
}
}
}