android - 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 时保留单例实例的正确方法是什么?
解决方案
好的,我的问题是我添加@Singleton
到由@ContributesAndroidInjector
. 正如gk5885 对类似问题的回答所指出的那样:
@Subcomponents 不能成为@Singleton。
原因是,由于子组件可能被组件重新创建,@Singleton 实例将仅对子组件实例保持相同。解决方案是从子组件和移动模块中删除@Singleton
注释,为根组件提供单例,然后将其标记为@Singleton
.
推荐阅读
- c# - 使用 Web API 对 JWT 令牌进行单元测试
- ios - 如果我运行一个空的 iOS 应用程序,我的手机在做什么?
- ruby-on-rails - rails + rspec:错误重复或已存在“as:”路线,但我没有任何重复
- r - 按索引和其他列值堆叠列值范围
- javascript - 使用 jQuery 从绝对路径的外部文件加载 HTML
- javascript - 在反应原生android上找不到变量
- performance - 非线性轨迹 - 计算还是保存?
- c# - 相机在 X 轴上移动但不在 Y 轴上
- python - Python:在一张图中绘制所有分类子集组合
- javascript - 检测 div 是否在屏幕的某个部分