【问题标题】:Dagger 2: DaggerBroadcastReceiver recreates SubcomponentDagger 2:DaggerBroadcastReceiver 重新创建子组件
【发布时间】:2021-01-06 19:53:19
【问题描述】:

假设我想要一个应用程序范围的 SomeSingletonClass 实例。我创建了一个提供此类对象的 Dagger 模块:

@Module
public interface MyModule {

    @Provider
    @Singleton
    SomeSingletonClass provideSomeSingletonClass() {
       return new SomeSingletonClass();
    }
    

我也想用 BroadcastReciever:

public class MyReceiver extends DaggerBroadcastReceiver {

    @Inject
    SomeSingletonClass someSingletonClass;

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        ...
    }
}

它有自己的模块:

@Module
public abstract class MyReceiverModule {
    @Singleton
    @ContributesAndroidInjector(modules = {MyModule.class})
    abstract MyReceiver myReceiver();
}

现在,对onReceive() 的每次调用都会导致对super.onReceive() 的调用,而super.onReceive() 又会调用AndroidInjection.inject(this, context)。这会导致重新创建 MyReceiver 的子组件和相关的依赖项,包括 SomeSingletonClass

使用 DaggerBroadcastReceiver 时保留单例实例的正确方法是什么?

【问题讨论】:

  • @Singleton 只是 Dagger 库附带的默认 @Scope 注释。 @Scope 只要求作用域组件/子组件与作用域依赖项相匹配——这意味着它们的“作用域”相同(这就是你所拥有的——你的“作用域”对象与同一作用域的子组件一样长)。如果您需要单个实例,则需要将其范围限定为根父组件,通常在 Android 中的 Application 类中创建。如果您需要自定义@Scope,只需创建一个,为您的根组件保留@Singleton

标签: android dependency-injection broadcastreceiver dagger


【解决方案1】:

好的,我的问题是我将@Singleton 添加到@ContributesAndroidInjector 创建的子组件中。正如 gk5885 在answer 中指出的类似问题:

不能将@Subcomponents 设为@Singleton。

原因是,由于子组件可能被组件重新创建,@Singleton 实例将仅对子组件实例保持相同。解决方案是从子组件中删除@Singleton注解,并将为根组件提供单例的移动模块,然后将其标记为@Singleton

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多