Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
pdegand59 Avatar asked Mar 15 '23 00:03

pdegand59


1 Answers

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/

like image 140
froger_mcs Avatar answered Mar 23 '23 02:03

froger_mcs