breakline
breakline

Reputation: 6073

Dagger2 allow injection to be null

So, in short, I have a lot of flavors of the same app with slight differences. I would like to add a Navigator for all flavors independently. I'm using Dagger2, and I have a sub component for each flavor where I inject things only for a given flavor. So I would like to inject a Navigator class too.

The trick is, that some of the classes in the common code use this navigator too, with a null check. So if it's null, fine, but if not then do x.

So I'd like to have a field like:

@Inject @Nullable Navigator navigator;

Dagger gives me an error if there is no @Provides method for something like this, but that's exactly what I want, I want the @Provides to go in the submodules but still inject in the common code base.

How can I achieve this?

Upvotes: 2

Views: 6261

Answers (2)

bsautner
bsautner

Reputation: 4812

if you don't want to go down the road of having nullable objects injected, you can return an Optional<Navigator> in your dagger module - you'll end up with cleaner code in the long run.

Upvotes: 2

David Medenjak
David Medenjak

Reputation: 34532

To support a nullable type you just have to add a @Nullable annotation on your @Provides method that returns the nullable type and Dagger will accept it.

If you don't, Dagger will complain that you can only provide nullable types from @Nullable annotated methods.

Upvotes: 6

Related Questions