1

I have a silly question to ask about Dagger 2. Because I want to be sure. I know that in compile time, Dagger generates code. But for the following code:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
          //build main component along with core component
         mainComponent = DaggerMainComponent
                .builder()
                .myModule(MyModule())
                .coreComponent(DaggerCoreComponent.builder().build())
                .build()
     }
}

Does Dagger call the build() to build the component to draw the dependency graph at compile time or runtime? My understanding is it's at runtime, am I right?

If I am correct above, what about the following code ?:

@Module(subcomponents = MySubComponent.class)
abstract class MyModule {
  ...
}

My understanding is with this Dagger automatically detects whether the MySubComponent is requested & if not it doesn't generate dependencies hosted in MySubComponent. But does this process happen at runtime or compile time?

Leem
  • 17,220
  • 36
  • 109
  • 159

1 Answers1

1

The dependency graph is built at compile time via annotation processing. Dagger will generate classes like that DaggerMainComponent from your example, based on the annotations that you added to your classes, like @Module, @Component, @Inject, etc.

I would suggest you to read an article about, annotation processing, like this one:

So what is Annotation Processing? Annotation is sort of tag mechanism you can label some meta on Classes, Methods or Parameters and Annotation Processing will analyze those Annotations in compile time and generate Classes for you according to your Annotations.

build() is called at runtime, you can open the code of DaggerMainComponent and check the implementation of the build method, it will be creating some instances of dependent modules, checking other requirements and finally creating a new instance of DaggerMainComponent.

Gustavo Pagani
  • 6,583
  • 5
  • 40
  • 71