Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional injection Dagger 2

Is it possible to optionally inject a value in dagger 2? In particular, I want to do something like this.

@Inject A(Optional<B> b) {
  this.b = b;
}

If B is undefined in the modules, I would want dagger to give an Optional.empty(), If it is defined then give Optional.of(value).

Is this doable or do I need a module that defines those optional values?

like image 373
Cogman Avatar asked Aug 26 '16 22:08

Cogman


Video Answer


1 Answers

Optional injection requires a module to add an optional binding to your component as Dagger requires every dependency, even an explicitly missing one, on the dependency graph. When you want to fulfill this optional with an implemention you will add an impl binding module to a component, normally a subcomponent, which wants to fulfill it.

The following is a what a Module should look like:

@Module
public interface OptionalModule {
  @BindsOptionalOf
  Foo bindOptionalFoo();
}

and

@Module
public interface ImplModule {
  @Binds
  Foo bindFooImpl(FooImpl foo);
}

Then you can constructor or member inject Optional

public class Bar {
  @Inject
  public Bar(Optional<Foo> optionalFoo) {}
}

or

public class Bar {
  @Inject
  public Optional<Foo> optionalFoo;
}
like image 101
MinceMan Avatar answered Oct 19 '22 12:10

MinceMan