In the below code, I have a module where I call @InstallIn(SingletonComponent::class)
. So the scope of this module is the application scope or singleton scope))
If I'll provide something inside the module, do I need to annotate that function with singleton
as well?
CodePudding user response:
Yes you have to annotate that function with singleton as well.
@InstallIn(SingletonComponent::class)
means that you may use singleton in your @Provides functions, without it you can't make your @Provides functions singleton. In hilt @Provides functions have no-scope by default so if you don't annotate your @Provides function with singleton, every time it will return new object.
you can easily test my answer with below code
var count = 0
class TestingClass() {
init {
count
}
fun printCount() = println("count: $count")
}
@Module
@InstallIn(SingletonComponent::class)
class TestModule {
@Provides
@Singleton // without this count will increase every time you inject TestingClass
fun provideTestClass(): TestingClass {
return TestingClass()
}
}