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?