【发布时间】: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