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

后端 未结 5 868
既然无缘
既然无缘 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 18:10

    Well you can manually create an annotation,which will help to create a singleton object.

    @Scope
    @Retention(RetentionPolicy.CLASS)
    public @interface MyApplicationScope {
    }
    

    When @MyApplicationScope annotation is added with @Provides annotation than it makes dagger to create an object only once and use same object in future. Do remember to add this annotation to the component interface also otherwise you will get the scope related error during compilation.

    If you are using @Singleton annotation then you may end up creating the new objects every time when you will create your component with .build().

提交回复
热议问题