Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

android - Dagger 2: DaggerBroadcastReceiver recreates Subcomponent

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, the problem in my case was that I added @Singleton to subcomponent created by @ContributesAndroidInjector. As pointed out in the answer by gk5885 to similar question:

@Subcomponents cannot be made @Singleton.

The reason is that, since subcomponent may be recreated by component, the @Singleton instance will be kept the same for the subcomponent instance only. The solution was to remove @Singleton annotation from subcomponents and the move module providing singleton to the root component, which was then marked as a @Singleton.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...