2

In all Android projects I posted on Google Play I've always used for dependency injection Roboguice. Recently I was able to see the benefits of Roboguice 3.0 and then I decided to investigate other libraries on Android for dependency injection not pigeonhole with Roboguice only. And how i found Dagger, and found an attractive concept, LAZY INJECTION, also I read the articule Dagger vs. Guice.

  • Does Roboguice this functionality or something like this?
  • If not, the limitation is given because Roboguice use reflection and Dagger works by generating code up front?
Jose Rodriguez
  • 9,753
  • 13
  • 36
  • 52

1 Answers1

4

Lazy is just a box that defers resolving the binding. It's extremely similar to Provider except with one important distinction: it will cache the value from the first call and return it on subsequent calls.

For bindings to singletons, there is no behavior difference from the consumer perspective. Both a Lazy<Foo> and a Provider<Foo> will both lazily look up the binding and return the same instance each time.

The only behavior change is when you have a non-singleton binding.

You can implement Lazy yourself with Guice like this:

public interface Lazy<T> { T get() }

public final class LazyProvider<T> implements Lazy<T> {
  private static final Object EMPTY = new Object();

  private final Provider<T> provider;
  private volatile Object value = EMPTY;

  public LazyProvider(Provider<T> provider) {
    this.provider = provider;
  }

  @Override public T get() {
    Object value = this.value;
    if (value == EMPTY) {
      synchronized (this) {
        value = this.value;
        if (value == EMPTY) {
          value = this.value = provider.get();
        }
      }
    }
    return (T) value;
  }
}

// In your module:

@Provides Lazy<Foo> provideLazyFoo(Provider<Foo> foo) {
  return new LazyProvider<Foo>(foo);
}
Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • 1
    Nice. But I think `ProvidedLazy` would be a less confusing name, as `LazyProvider` takes a `Provider` as a parameter but not a `Provider` itself and then it is provided as `Lazy`... what? :) – Dmitry Zaytsev May 22 '15 at 09:57