-
Notifications
You must be signed in to change notification settings - Fork 0
Hilt β Constructor Injection
Devrath edited this page Oct 8, 2023
·
4 revisions
Contents |
|---|
| Observations |
| Output |
| Code |
// ----------> Class is loaded for the first time
Wheels constructor is invoked !
Engine constructor is invoked !
Car constructor is invoked !
// ----------> Clicking the button to access the instance to perform an action the first time
Car instance -> 137539380
Car is Driving with com.istudio.di.modules.dagger.demos.concepts.implementations.vehicle.Wheels@52ea15d and with com.istudio.di.modules.dagger.demos.concepts.implementations.vehicle.Engine@4f33ad2
// ----------> Device is rotated
Wheels constructor is invoked !
Engine constructor is invoked !
Car constructor is invoked !
// ----------> Clicking the button to access the instance to perform an action the second time
Car instance -> 145556911
Car is Driving with com.istudio.di.modules.dagger.demos.concepts.implementations.vehicle.Wheels@dc0edbc and with com.istudio.di.modules.dagger.demos.concepts.implementations.vehicle.Engine@efcb145
// ----------> Clicking the button to access the instance to perform an action a third time but now without rotation
Car instance -> 145556911
Car is Driving with com.istudio.di.modules.dagger.demos.concepts.implementations.vehicle.Wheels@dc0edbc and with com.istudio.di.modules.dagger.demos.concepts.implementations.vehicle.Engine@efcb145
Contents |
|---|
| Implementation |
| 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 with $wheels and with $engine") }
}MyActivity.kt
@AndroidEntryPoint
class HiltConstructorInjectionActivity : AppCompatActivity() {
private lateinit var binding: ActivityHiltConstructorInjectionBinding
@Inject lateinit var car: Car
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHiltConstructorInjectionBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListeners();
}
private fun setOnClickListeners() {
binding.apply {
initiateId.setOnClickListener {
PrintUtils.printLog("Car instance -> "+car.hashCode().toString())
car.start()
}
}
}
}