Hilt ‐ Scoping with just @Singletion annotation and without @SingletonComponent annotation - devrath/DroidDi GitHub Wiki
Observation
- Observe that I have annotated the implementation class
HiltAnalyticsServicewith@Singleton. - Note we do not have a
@Singletoncomponent. - Still not that when you rotate the Activity the Injected class is not re-instantiated which can be seen in the address printed.
Output
// When activity is loaded for the first time
HiltAnalyticsService class is built
// Click on the Button to call the injected reference in activity for the first time
Reference address:-> 72836706
// Click on the Button to call the injected reference in activity for the second time
Reference address:-> 72836706
// When you rotate the screen
// Click on the Button to call the injected reference in activity for the third time
Reference address:-> 72836706
Implementations
HiltAnalyticsService.kt
@Singleton
class HiltAnalyticsService @Inject constructor() {
init {
PrintUtils.printLog("HiltAnalyticsService class is built")
}
fun logAnalytics(data : String) {
PrintUtils.printLog("Reference address:-> $data")
}
}
Activity
MyActivity.kt
@AndroidEntryPoint
class HiltScopingActivity : AppCompatActivity() {
private lateinit var binding: ActivityHiltScopingBinding
@Inject lateinit var imageProcessingService : ImageProcessingService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHiltScopingBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListeners();
}
private fun setOnClickListeners() {
binding.apply {
notASingleTonId.setOnClickListener {
// Not a singleton
val code = imageProcessingService.hashCode().toString()
imageProcessingService.processImage(code)
}
}
}
}