Rubin Yoo
Rubin Yoo

Reputation: 2720

How to make subcomponent singleton in dagger 2?

I want to make my subcomponent to be a singleton so that I can have Login Presenter to be a singleton as well. Is this possible?

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
    LoginComponent getLoginComponent();
}

@Singleton
@Subcomponent(modules = LoginModule.class)
public interface LoginComponent {
}

public class LoginComponent {
    @Singleton
    LoginPresenter getLoginPresenter();
}

Upvotes: 2

Views: 1823

Answers (1)

gk5885
gk5885

Reputation: 3762

@Subcomponents cannot be made @Singleton.

While the @Singleton spec is a little vague about it, "singleton" canonically means "one per application". Since a @Subcomponent is created via a factory method on a component, the only way in which your singleton-bound instances would be "one per application" would be if the singleton subcomponent were a child of a singleton component and its factory method were only ever invoked once per application. Enforcing that constraint is virtually impossible, so the pattern would just be a likely source of bugs.

Upvotes: 4

Related Questions