Home > Net >  What is the purpose of @Singleton on a function (Hilt)
What is the purpose of @Singleton on a function (Hilt)

Time:11-29

In Android Hilt, you can apply the @Singleton annotation to a function like this:

@Module
@InstallIn(SingletonComponent::class)
object SomeModule {
    
    @Singleton
    @Provides
    fun provideSomething(): String {
        return "Hi there"
    }
}

I don't understand what the purpose of using a singleton on a function accomplishes. A class that has the @Singleton means that an instance of the class only exists once. But you cannot create instances of functions, so I don't see the point.

CodePudding user response:

@Singleton is called Scope and by default, all bindings in Hilt are unscoped. This means that each time your app requests the binding, Hilt creates a new instance of the needed type. For example in your case each time you request a String a new string is going to be created.

But when you add @Singleton annotation you said that the scope of this instance is singleton so it's going to provide the same instance each time you request a String.

Unlike SingletonComponent which is a component, it decide where you can use that module, so if you change it to ViewModelComponent for example you will be able to use that module only from ViewModel and it's lifecycle is going to be related to the ViewModel lifecycle.

You can take a look here for more information: https://developer.android.com/training/dependency-injection/hilt-android#generated-components

Take a look at this example:

instead of just providing a static string try to provide some random number:

@Provides
fun provideString(): String {
    return (1..100).random().toString()
}

Without @Singleton when you inject String in different classes in your App you will get different results because each time hilt is going to run the code inside provideString function so it's going to return a new instance of String ( that's what I mean by providing a new instance ).

Now add @Singleton:

@Singleton
@Provides
fun provideString(): String {
    return (1..100).random().toString()
}

You will notice that the provided String is the same across your app so provideString is called once and the result is saved so hilt is returning that saved instance of String every time.

CodePudding user response:

Functions can be singletons just like classes , It will assure only one instance will be created . Normally multiple calls of same function will be stacked , and performed one by one , while in a singleton function , last call will overwrite the previous one .so if you called it 10 times in a loop , no instances of the calls will be stacked in the memory.

  • Related