Singleton in Dagger on a method

Asked by At

In the Dagger documentation it shows this:

@Provides @Singleton static Heater provideHeater() {
  return new ElectricHeater();
}

I'm use to seeing singletons on classes where only a single instance of the class exists. What is the point of using @Singleton on a method? Even without Dagger, you don't get a single instance of a method. There are never multiple instances of a method regardless whether a class instance is a singleton or not. The docs state:

The graph will use a single instance of the value for all of its clients.

What exactly does that mean? Does it mean that every time the method is called, it returns the exact same instance of ElectricHeater?

1 Answers

2
EpicPandaForce On Best Solutions

You create a component that is also marked with @Singleton, and give it this @Module for it to be able to provide a Heater:

@Singleton
@Component(modules = HeaterModule.class)
public interface SingletonComponent {
    Heater heater();
}

Then you create an instance of this component as per usual with Dagger, and invoke the heater() method, you'll always get the same instance

SingletonComponent component = DaggerSingletonComponent.create();
Heater heater1 = component.heater();
Heater heater2 = component.heater();
assertThat(heater1).isSameAs(heater2); // heater1 == heater2

However if it were unscoped, or if you are talking to a different component instance, you'll get a different instance.

SingletonComponent component1 = DaggerSingletonComponent.create();
SingletonComponent component2 = DaggerSingletonComponent.create(); // probably a bug that you have *two* of a "singleton", but i've seen it before nonetheless
Heater heater1 = component1.heater();
Heater heater2 = component2.heater();
assertThat(heater1).isNotSameAs(heater2); // heater1 != heater2