Provider and Lazy Injections with Dagger2

Sometimes, when providing dependencies with Dagger, you may want to change how the instances of your dependencies are instantiated. Dagger gives us some options with two generic interfaces we can use at an injection site: Lazy and Provider. If you are new to Dagger, I would suggest reading the introductory article I wrote.

Lazy

Lazy allows us to instantiate an instance lazily. This means that the dependency will only be created once a method is called on it and then subsequently cached. Let’s look at an example.

The first logging statement will output 0, since SomeClass has not yet been instantiated. However, the second log will output 1. This is because the instance will only be created once Lazy’s get() method is called. Further calls to get() will not recreate the instance; it is cached when get() is called the first time. Note that Lazy does not work like a scoped binding, if we were to Lazy inject multiple instances of the same class via our constructor, they would all be unique instances – not the same.

Provider

Provider creates a new instance each time get() is called, this is essentially the opposite to how Lazy initialization works.

In this example, we’re calling get() three times. As you can probably guess, instantionCount will be 0 initially and then rise to 3 at the last log statement.

Direct Injection

But how does our class work without using Lazy or Provider? What about plain old direct injection?

Can you guess what the logs will say? Both logging statements will print 1. Why? This is because with direct injection, the instance is resolved and instantiated immediately. This is different to both Lazy and Provider where instantiation is deferred to their get() calls.

Wrap up

Now that you know how Provider, Lazy and direct injection works – you should have better control over how your dependencies are instantiated!

Liked the article? Share it!

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of