I've looked at a couple different articles which seem to suggest two different ways of doing custom scoping in Dagger 2:
MVP Presenters that Survive Configuration Changes Part-2 (Github repo):
- Uses unique custom scopes for each fragment, e.g.
@Hello1Scope
and@Hello2Scope
forHello1Fragment
andHello2Fragment
respectively
- Uses unique custom scopes for each fragment, e.g.
-
- Uses a single custom scope for all fragments, e.g.
@PerFragment
.
- Uses a single custom scope for all fragments, e.g.
From what I understand, it seems that, as in method 2, it should be okay to have a single scope defined that can be used for all fragments (i.e., @PerFragment
). In fact (please correct me if I'm wrong), it seems like the name of the custom scope is irrelevant, and it's only where the subcomponent is created (i.e. in Application, Activity, or Fragment) that matters.
Is there any use case for defining a unique scope for each fragment such as in case 1?
After reading the answer by @vaughandroid, and What determines the lifecycle of a component (object graph) in Dagger 2? I think I understand custom scopes well enough to answer my own question.
First, here are a couple rules when dealing with components, modules, and scoping annotations in dagger2.
@Singleton
or@CustomScope
).@Singleton
for the root Component (and it's modules) only. Subcomponents must use a custom scope, but the functionality of that scope is exactly the same as@Singleton
.Now, to answer the question: I would say create a new named scope for each conceptually different scope. For example, create a
@PerActivity
,@PerFragment
, or@PerView
annotation that indicates where the component should be instantiated, and thus indicating its lifetime.Note: this is a compromise between two extremes. Consider the case of a root component and n subcomponents you will need:
@Singleton
and@SubSingleton
), and@Singleton
,@SubSingleton1
, ...@SubSingletonN
).Example:
Application:
Fragment: