-
Notifications
You must be signed in to change notification settings - Fork 0
Hilt β Scoping with just @Singletion annotation and without @SingletonComponent annotation
Devrath edited this page Oct 9, 2023
·
2 revisions
- Observe that I have annotated the implementation class
HiltAnalyticsService
with@Singleton
. - Note we do not have a
@Singleton
component. - Still not that when you rotate the Activity the Injected class is not re-instantiated which can be seen in the address printed.
// 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
HiltAnalyticsService.kt
@Singleton
class HiltAnalyticsService @Inject constructor() {
init {
PrintUtils.printLog("HiltAnalyticsService class is built")
}
fun logAnalytics(data : String) {
PrintUtils.printLog("Reference address:-> $data")
}
}
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)
}
}
}
}