-
Notifications
You must be signed in to change notification settings - Fork 0
Hilt β Scoping with with both @Singletion and @SingletonComponent annotations
Devrath edited this page Oct 9, 2023
·
2 revisions
- Here when both annotation is used you can observe that when the class is loaded and the Instance is injected the instance class is instantiated.
- And the address remains even after multiple clicks.
- When you rotate the device the Instance class is
not
re-instantiated
and so the address still remains constant.
// When activity is loaded for the first time
HiltNetworkService 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
SerializationService.kt
class SerializationService @Inject constructor() {
init { PrintUtils.printLog("HiltNetworkService class is built") }
fun serializeData(data : String) {
PrintUtils.printLog("Reference address:-> $data")
}
}
HiltScopingApplicationModule.kt
@InstallIn(SingletonComponent::class)
@Module
object HiltScopingApplicationModule {
@Singleton
@Provides
fun getSerializationService() : SerializationService {
return SerializationService()
}
}
MyActivity.kt
@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
private lateinit var binding: ActivityHiltScopingBinding
@Inject lateinit var serializationService : SerializationService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHiltScopingBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListeners();
}
private fun setOnClickListeners() {
binding.apply {
singletonCompWithSingletonAnnotationId.setOnClickListener {
val code = serializationService.hashCode().toString()
serializationService.serializeData(code)
}
}
}
}