Sobes.tech
Middle+

What are the main differences between SubComponents and Component annotations in Dagger?

sobes.tech AI

Answer from AI

@Component  
interface AppComponent {  
    // ...  
}  
  
@Subcomponent  
interface UserComponent {  
    // ...  
}  
  
// Example of using Subcomponent in AppComponent  
@Component(modules = AppModules.class)  
interface AppComponent {  
    UserComponent userComponent(); // Adding a factory method  
}  

Component:

  • A self-sufficient dependency graph.
  • Acts as a root component or can be a dependency for other components (using dependencies).
  • Created using a factory method (create() or builder) in an annotated interface.

Subcomponent:

  • Extends the parent component's graph.
  • Has access to all dependencies provided by the parent component.
  • Does not have its own dependencies (via dependencies).
  • Created by the parent component through a factory method.
  • Allows creating more modular and manageable graphs.