How to make subcomponent singleton in dagger 2?

穿精又带淫゛_ 提交于 2019-12-11 13:29:46

问题


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();
}

回答1:


@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.



来源:https://stackoverflow.com/questions/37797519/how-to-make-subcomponent-singleton-in-dagger-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!