Search code examples
dagger-2

Can dagger subcomponent builder set data (other than module)?


In reference to Dagger 2 Subcomponent Documentation, the example code shows that

@Singleton
class RequestRouter {
  @Inject RequestRouter(
      Provider<RequestComponent.Builder> requestComponentProvider) {}

  void dataReceived(Data data) {
    RequestComponent requestComponent =
        requestComponentProvider.get()
            .data(data)  // Data could be set here?
            .build();
    requestComponent.requestHandler()
        .writeResponse(200, "hello, world");
  }
}

From what I understood, that Subcomponent.Builder can only set the Module and Build, as per https://dagger.dev/api/2.10/dagger/Component.Builder.html

Just wonder how could we pass Data into the builder?


Solution

  • Always make sure to read the latest JavaDoc, 2.10 is quite old (Mar 20, 2017). I believe @BindsInstance was introduced with Dagger 2.12:

    • [...]
    • There may be setter methods annotated with @BindsInstance. These methods bind the instance passed to them within the component. See @BindsInstance for more information.
    • [...]

    You can add various bindings to your component, e.g.

    @BindsInstance
    Builder foo(Foo foo); // allow binding of some `Foo`