0

I have a Dagger2 @Module class with the @Provides annotated method which calls Retrofit.create method:

@Provides
RestService provideRestService(final Retrofit retrofit) {
    return retrofit.create(RestService.class);
}

Should I annotate this method with the @Singleton annotation?

I see one reason to do it: calling create each time has some cost and one reason for not doing it: keeping one instance has some cost (Dagger performs double checking each time instance is requested).

Which solution is preferred? With or without @Singleton annotation? Or maybe it is not important at all? Or my approach to create this class in provider is fundamentally wrong?

2 Answers2

3

If additional instances are allowed but potentially-expensive, you might also consider the use of @Reusable. You lose double-checked locking, but you (potentially) shorten object lifespans and gain flexibility about where the instances are installed.

@Reusable is useful when you want to limit the number of provisions of a type, but there is no specific lifetime over which there must be only one instance.

See the User's Guide topic or the SO question Dagger @Reusable scope vs @Singleton.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
0

Yes, you should. You avoid memory allocation. Android will keep you the same instance untill the app is killed. Think about if you call the api like into a for loop and each time you create a new instance (not recommended and won't happen when you use dagger in same injectionm but just like an example). It will kill your memory. So you should use @Singleton.

Singleton will ensure you that you will use the same instance across module.

Cătălin Florescu
  • 5,012
  • 1
  • 25
  • 36