Ad

How To Share Dagger2 Subcomponent Between Activities

- 1 answer

I was wondering on how to share subcomponent between activities?

Let's say I have a global AppComponent that lives with the Application.

I want to have a UserComponent that lives across multiple activities when the user is actually logged in my application.

When the user logs in, my app create a UserComponent that other activities has to retrieve from somewhere, but I don't know what is the best "somewhere".

Should I store the UserComponent in the Application and create a getter and a method that reset the component? Should I place this component inside an "holder" object inside the ApplicationModule and in every sub activity, retrieve my component by getting the "holder" from the ApplicationComponent? Should I just stores it in a static field? Should I do something else?

Ad

Answer

Because you're responsible for subcomponent lifecycle I would store it in Application object with additional getter and setter. There is only place which lives all the time and can store global objects.

Wrapper? Yes, if you would like to have more complicated lifecycle, but still it will be stored in Application.

What you have to remember is that Application object can be also killed, so you should be able to restore your UserComponent.

Here you have my simple case with source code which shows how UserComponent can work: http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/

Ad
source: stackoverflow.com
Ad