Package dagger
Interface Lazy<T>
-
public interface Lazy<T>A handle to a lazily-computed value. EachLazycomputes its value on the first call toget()and remembers that same value for all subsequent calls toget().All implementations are expected to be thread-safe and compute their value at most once.
Example
The differences between direct injection, provider injection and lazy injection are best demonstrated with an example. Start with a module that computes a different integer for each use:@Module final class CounterModule { int next = 100; @Provides Integer provideInteger() { System.out.println("computing..."); return next++; } }Direct Injection
This class injects that integer and prints it 3 times:
Injecting afinal class DirectCounter { @Inject Integer value; void print() { System.out.println("printing..."); System.out.println(value); System.out.println(value); System.out.println(value); } }DirectCounterand invokingprint()reveals that the value is computed before it is required:computing... printing... 100 100 100Provider Injection
This class injects a provider for the integer. It callsProvider.get()3 times and prints each result:
Injecting afinal class ProviderCounter { @Inject Provider<Integer> provider; void print() { System.out.println("printing..."); System.out.println(provider.get()); System.out.println(provider.get()); System.out.println(provider.get()); } }ProviderCounterand invokingprint()shows that a new value is computed each timeProvider.get()is used:printing... computing... 100 computing... 101 computing... 102Lazy Injection
This class injects aLazyfor the integer. Like the provider above, it callsLazy.get()3 times and prints each result:
Injecting afinal class LazyCounter { @Inject Lazy<Integer> lazy; void print() { System.out.println("printing..."); System.out.println(lazy.get()); System.out.println(lazy.get()); System.out.println(lazy.get()); } }LazyCounterand invokingprint()shows that a new value is computed immediately before it is needed. The same value is returned for all subsequent uses:printing... computing... 100 100 100Lazy != Singleton
Note that each injectedLazyis independent, and remembers its value in isolation of otherLazyinstances. In this example, twoLazyCounterobjects are created andprint()is called on each:
The output demonstrates that eachfinal class LazyCounters { @Inject LazyCounter counter1; @Inject LazyCounter counter2; void print() { counter1.print(); counter2.print(); } }Lazyworks independently:
Useprinting... computing... 100 100 100 printing... computing... 101 101 101@Singletonto share one instance among all clients, andLazyfor lazy computation in a single client.
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description Tget()Return the underlying value, computing the value if necessary.
-
-
-
Method Detail
-
get
T get()
Return the underlying value, computing the value if necessary. All calls to the sameLazyinstance will return the same result.
-
-