Minh Nghĩa
Minh Nghĩa

Reputation: 1053

@Singleton vs @InstallIn(SingletonComponent::class)

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.

Upvotes: 8

Views: 4614

Answers (4)

EMEM
EMEM

Reputation: 3148

@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(){
        ...
    }
}

Upvotes: 4

tugceaktepe
tugceaktepe

Reputation: 407

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.

Upvotes: 0

Mahdi Zareei
Mahdi Zareei

Reputation: 152

@SingletonComponent specifies that it can be used in the entire application.

@Singleton is a software design pattern causes the object to be initialized once.

Upvotes: 0

Saeid Lotfi
Saeid Lotfi

Reputation: 2137

ApplicationComponent being renamed to SingletonComponent, to allow usage of Hilt in non-Android Gradle modules link

but @Singleton is a software design pattern link

Upvotes: -1

Related Questions