Order Of Dependency Injection When Using Scopes
Solution 1:
To my best knowledge, Dagger-2 doesn't support "partial injections".
Therefore, when you call myComponent.inject(this), Dagger-2 throws an error if myComponent can't provide all @Inject annotated members of this.
I see two ways to work around this limitation:
- Remove
@Injectannotation fromUserProfile, exposeUserProfilevia public method inUserComponentand inject it manually whenUserComponentis ready to be used. Something analogous to this:userProfile = userComponent.getUserProfile() - Don't make
UserComponentdependent on data fetching.UserComponentcould be used to injectToolbarand someUserProfileProviderat the same time, and you will fetchUserProfilefromUserProfileProviderwhen it is available.
I personally think that second approach is the better choice. DI libraries should be used in order to satisfy objects' dependencies at construction time. In Android we can't construct Activity or Fragment ourselves, therefore we perform DI in onCreate(), onAttach(), onCreateView(), etc., but it does not mean that we should be using DI libraries in order to assist in controlling the flow of applications.
Solution 2:
Subcomponents work's similar to inheritance(extends), in your case User component and Activity component extending App component but there is no relation between User component and Activity component so when you request User dependency in Activity it will fail.
Subcomponent can't provide any dependency to other Subcomponent.
Instead, you can make Activity component as a subcomponent of User component. This will also give you the flexibility to switch user.
Post a Comment for "Order Of Dependency Injection When Using Scopes"