Junior — Middle
What is the difference between using Lazy and Provider in Dagger when injecting dependencies?
sobes.tech AI
Answer from AI
In Dagger, Lazy and Provider are used for deferred dependency retrieval but have different characteristics:
-
Lazy<T>— provides an instance ofTupon the first call toget(), then returns the same instance (caches the result). Used when you want to delay object creation until first use but ensure a singleton instance. -
Provider<T>— creates a new instance ofTevery timeget()is called. Used when a new object is needed each time.
Example:
class MyClass @Inject constructor(
private val lazyDependency: Lazy<Dependency>,
private val providerDependency: Provider<Dependency>
) {
fun useLazy() {
val instance1 = lazyDependency.get()
val instance2 = lazyDependency.get() // instance1 == instance2
}
fun useProvider() {
val instance1 = providerDependency.get()
val instance2 = providerDependency.get() // instance1 != instance2
}
}