0

I am using Java and Dagger dependency injection framework. Often I have situations where I have to init a class but used later e.g.:

private final Message message;

public SomePresenter() {
  message = DaggerComponent.getMessage();
}

public someFuncA() {
  message.doSomething();
}

public someFuncB() {
  message.doSomething();
}

I want that message is initialized the first time it is requested and from that moment alway use the same message instance in this class. How can I do that?

Edit:

I tried to use Lazy as follows but lazyMessage is undefined:

public class StartPresenter {

  @Inject
  Lazy<Message> lazyMessage; 

  @Inject
  public StartPresenter(ConfigObject config) {
  }

}

Here is my dagger2 configuration:

@Component(modules = {ApplicationModule.class})
@Singleton
public interface ApplicationComponent {

   Message getMessage();
}

@Module()
public class CoreModule {

  @Provides @Singleton
  Message provideMessage() {
    return new MessageImpl();
  }  
}

How do I get lazyMessage being instantiated by dagger?

Michael
  • 32,527
  • 49
  • 210
  • 370

1 Answers1

3

Use the Lazy class like

@Inject Lazy<Message> message;

In your code use:

//Doing something with message
message.get().messageMethod();

Here's the documentation for Lazy

Dagger will only wire up the class when get() is called. It will return the same instance everytime get() is called.

Michael
  • 32,527
  • 49
  • 210
  • 370
yxre
  • 3,576
  • 21
  • 20