首页 > 解决方案 > Dagger 2:DaggerBroadcastReceiver 重新创建子组件

问题描述

假设我想要一个单一的、应用程序范围的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()而调用又会调用AndroidInjection.inject(this, context). 这会导致重新创建子组件MyReceiver和相关的依赖项,包括SomeSingletonClass.

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

标签: androiddependency-injectionbroadcastreceiverdagger

解决方案


好的,我的问题是我添加@Singleton到由@ContributesAndroidInjector. 正如gk5885 对类似问题的回答所指出的那样:

@Subcomponents 不能成为@Singleton。

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


推荐阅读