I realize that the recommended way of accomplishing Lazy injection with Dagger is to add Lazy to a field injection point. For instance,
class Foo {
@Inject lateinit var bar: Lazy<Bar>
fun useBar() = bar.get().doSomething()
}
What about using constructor injection? I have not seen anyone doing it.
class Foo @Inject constructor(private val fizz: Fizz,
private val bar: Lazy<Bar>) {
fun useBar() = bar.get().doSomething()
}
To summarize when doing Dagger lazy injection, can I use Lazy<Bar> in a constructor? Or is my only option to move Lazy<Bar> to a field injection while keeping other non-Lazy dependencies in the same class injected via the constructor?
Thanks for any pointers!
Constructor injection is no different from regular field injection, Lazy-wrapped constructor arguments are acceptable.
The only thing you need to make sure is to expose the dependency via module somewhere in the dependency graph.
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