MyoZaw Oo
MyoZaw Oo

Reputation: 127

Dagger 2 Custom Scope for each Activity

Do I need to create each scope for every single activity? Can't I define only a default scope for every activity for fragment?

Upvotes: 0

Views: 344

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95634

You can easily have an @ActivityScope or @ActivityScoped object applied to multiple sibling activity components, and it will work the way you expect: As long as you create exactly one new subcomponent per activity instance, then each will have access to @ActivityScope bindings that will live in their respective components.

@ApplicationScope @Component(/* ... */)
interface ApplicationComponent {
  FooActivitySubcomponent createFoo();
  BarActivitySubcomponent createBar();
  // ...
}

@ActivityScope @Subcomponent(/* ... */)
interface FooActivitySubcomponent {
  void inject(FooActivity activity);
  // ...
}

@ActivityScope @Subcomponent(/* ... */)
interface BarActivitySubcomponent {
  void inject(BarActivity activity);
  // ...
}

Of course, Module.subcomponents is a better way to specify subcomponents in production, and of course dagger.android is an automatic way to create a structure like this.

Upvotes: 1

Related Questions