Assume I want to have a single, application-wide instance of SomeSingletonClass
. I created a Dagger module which provides such object:
@Module
public interface MyModule {
@Provider
@Singleton
SomeSingletonClass provideSomeSingletonClass() {
return new SomeSingletonClass();
}
I also want to use BroadcastReciever:
public class MyReceiver extends DaggerBroadcastReceiver {
@Inject
SomeSingletonClass someSingletonClass;
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
...
}
}
It has its own module:
@Module
public abstract class MyReceiverModule {
@Singleton
@ContributesAndroidInjector(modules = {MyModule.class})
abstract MyReceiver myReceiver();
}
Now, each call to onReceive()
causes a call to super.onReceive()
which in turn calls AndroidInjection.inject(this, context)
. This causes to recreate subcomponent of MyReceiver
and associated dependencies, including SomeSingletonClass
.
What is the proper way to preserve singleton instances when using DaggerBroadcastReceiver?
question from:
https://stackoverflow.com/questions/65602564/dagger-2-daggerbroadcastreceiver-recreates-subcomponent 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…