Search code examples
androidcode-injectionroboguicedagger

Lazy injection with Roboguice


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?

Solution

  • 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);
    }