简体   繁体   中英

How to share Dagger2 Subcomponent between activities

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM