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(){
...
}
}
@SingletonComponent specifies that it can be used in the entire application.
@Singleton is a software design pattern causes the object to be initialized once.
Instances of components provided in the modules specified as
@InstallIn(SingletonComponent::class)
live throughout the application lifecycle.So, it refers component's lifetime.
While using injections(such as field or constructor), Hilt provides the instance of the components. If we want these components also created only once, we should add the @Singleton
scope annotation. If we do not add this, a new instances are constantly created.
However scoping a binding to a component can be costly because the provided object stays in memory until that component is destroyed. That's why by default, all bindings in Hilt are unscoped, you need to use them according to your needs. You can read the details in Android official website.
ApplicationComponent
being renamed to SingletonComponent
, to allow usage of Hilt in non-Android Gradle modules link
but @Singleton
is a software design pattern link
ApplicationComponent
too, but I thought it wasn't relevant so I didn't ask about it. –
Overfill @Singleton
and @InstallIn(SingletonComponent::class)
effectively the same? Because there can be only 1 SingletonComponent
/ApplicationComponent
(I think so). –
Overfill @Singleton
only applies to 1 "container", then there can be n
instances across n
different containers, and in that case, I'm definitely wrong. –
Overfill @Singleton
used in dagger is singleton double check pattern
and in the app you just have a instance, but multithreading can cause the have n
instance without @Singleton
–
Ruminate © 2022 - 2024 — McMap. All rights reserved.