Dagger 2 - what is the purpose of a @Singleton annotation class

后端 未结 5 938
既然无缘
既然无缘 2021-02-03 17:43

From the dagger 2 Documentation I noticed that you can have a @Singleton annotated class. What is the purpose of marking a class as @Singleton as I hav

5条回答
  •  不要未来只要你来
    2021-02-03 17:56

    @Singleton does not really create a Singleton, it is just a Scope, it is advised to not use @Singleton as it is misleading, it gives the impression that we are infact getting a Singleton, but we are not.

    Let's say you annotate your database dependency with @Singleton and link with a Component, now let's say that you initialise this Component in Activities A and B, you will have different instances of your database in your two Activities which is something most people don't want.

    How do you overcome this?

    Initialise your Component once in your Application class and access it statically in other places like Activities or Fragments, now this could soon get out of hand if you have more than 20 Component's as you cannot initialise all of them in your Application class, doing so will also slow down your app launch time.

    The best solution according to me is to create a real Singleton, either double checked or of other variants and use this statically as getInstance() and use this under @Provides in your Module.

    I know it breaks my heart too, but please understand that @Singleton is not really a Singleton, it's a Scope.

提交回复
热议问题