Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@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.

like image 973
Minh Nghĩa Avatar asked Jul 01 '26 06:07

Minh Nghĩa


1 Answers

@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(){
        ...
    }
}
like image 166
Ehsan Mashhadi Avatar answered Jul 02 '26 22:07

Ehsan Mashhadi