'Dagger 2 extending interfaces vs dependent components

In Dagger I sometimes see that there are components that just extend an interface while others use the dependencies.

So for example we have a base component:

@Singleton
@Component(modules={...})
public interface BaseComponent {
    ...
}

Version 1:

@Singleton
@Component(modules={...})
public interface MyComponent extends BaseComponent {
    ...
}

And Version 2:

@CustomScope
@Component(modules={...}, dependencies= BaseComponent.class)
public interface MyComponent {
    ...
}

Are they used for different scenarios?



Solution 1:[1]

If you want to create a hierarchy of components, the standard ways to do this are to use subcomponents or to use dependent components.

You can use interface extension to make test components. This is a better solution than extending modules. See here for an explanation from the official docs:

@Component(modules = {
  OAuthModule.class, // real auth
  FooServiceModule.class, // real backend
  OtherApplicationModule.class,
  /* … */ })
interface ProductionComponent {
  Server server();
}

@Component(modules = {
  FakeAuthModule.class, // fake auth
  FakeFooServiceModule.class, // fake backend
  OtherApplicationModule.class,
  /* … */})
interface TestComponent extends ProductionComponent {
  FakeAuthManager fakeAuthManager();
  FakeFooService fakeFooService();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1