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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With