What's the difference between these two? I think they both annotate a singleton object/instance, but somehow @Singleton can be used to annotate methods, instead of classes. I'm really confused about both of them.
@InstallIn(X) indicates in which (X here) DI container (generated by HILT automatically) the module bindings should be available. It's related to the lifetime of the dependencies.
For example:
@InstallIn(SingletonComponent::class)
object ApiModule {
@Provides
fun provideRetrofit(){
...
}
}
The above example means the ApiModule is bound to the application class, so this will exist as long as the application exists, but every time the Hilt tries to provide the Retrofit instance it will create a new object. However, if we add @Singleton then it will return the same Retrofit instance every time:
@InstallIn(SingletonComponent::class)
object ApiModule {
@Provides
@Singleton
fun provideRetrofit(){
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With