如何使匕首2中的子组件单例? [英] How to make subcomponent singleton in dagger 2?

查看:60
本文介绍了如何使匕首2中的子组件单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将我的子组件设置为单例,以便我也可以使Login Presenter也成为单例。

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


推荐答案

@Subcomponent 不能做成 @Singleton

@Singleton 规范对此有点含糊, singleton通常表示每个应用程序一个。由于 @Subcomponent 是通过工厂方法在组件上创建的,因此 only 方式中,与单例绑定的实例为每个应用程序一个 如果单例子组件是单例组件的子代,并且其工厂方法在每个应用程序中仅被调用一次。强制执行该约束实际上是不可能的,因此该模式仅可能是错误的来源。

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.

这篇关于如何使匕首2中的子组件单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆