Create Subcomponent — Dagger 2
Subcomponent: It is a component that inherits and extends the object graph of a parent component. It defines with @subcomponent annotation.
Advantages: It helps to partition your application’s object graph into subgraphs
1. To encapsulate different parts of your application from each other i.e using the Abstract Factory pattern
2. To use more than one scope within a component.
Important:
Objects bound in parent components can’t bound again in subcomponents, nor objects bound in one subcomponent depend on objects bound in sibling subcomponents if you use there will be a CompilationFailedException.
Declaring a subcomponent:
Except for annotation difference, Subcomponent’s creation very similar to component’s creation. Subcomponent uses @Subcomponent annotation and for custom builder user @Subcomponent.Builder.
@Subcomponent(modules = {
CModule.class,
DModule.class
})
public interface AppSubComponent {
@Subcomponent.Builder
interface AppSubComponentBuilder {
AppSubComponent build();
}
}
Adding a subcomponent to a parent component:
Create a module class for your subcomponent with annotation @module. This module annotation will bound AppSubComponent using subcomponents
attribute of @Module as given below.
Now add this AppSubComponentModule module class into your parent component class i.e AppComponent.
@Module(subcomponents = AppSubComponent.class)
public class AppSubComponentModule {
}
After adding AppSubComponentModule into AppComponent class, class structure will be like given below:
@Singleton
@Component(
modules = {
AModule.class,
BModule.class,
ActivityModule.class,
AppSubComponentModule.class,
AndroidInjectionModule.class,
AndroidSupportInjectionModule.class,
}
)
public interface AppComponent extends AndroidInjector<ABCDofDaggerApplication> {
}
That’s all about subcomponent creations. About Subcomponent and scope, subcomponent for encapsulation(Abstract factory design pattern) and multi-binding with subcomponents will be covered in separate stories.
Let’s make happily coding journey with a clap. :-)