Sobes.tech
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 of T upon the first call to get(), 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 of T every time get() 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
    }
}
What is the difference between using Lazy and… - sobes.tech