简体   繁体   English

匕首不会初始化惰性 <T> 懒变量?

[英]Dagger does not initialize Lazy<T> lazy Variable?

I am using Java and Dagger dependency injection framework. 我正在使用Java和Dagger依赖项注入框架。 Often I have situations where I have to init a class but used later eg: 通常,我不得不初始化一个类,但后来使用它,例如:

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 : 我尝试如下使用Lazy ,但是lazyMessage是undefined

public class StartPresenter {

  @Inject
  Lazy<Message> lazyMessage; 

  @Inject
  public StartPresenter(ConfigObject config) {
  }

}

Here is my dagger2 configuration: 这是我的dagger2配置:

@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? 如何使lazyMessage被匕首实例化?

Use the Lazy class like 使用像Lazy这样的类

@Inject Lazy<Message> message;

In your code use: 在您的代码中使用:

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

Here's the documentation for Lazy 这是Lazy的文档

Dagger will only wire up the class when get() is called. Dagger仅在调用get()时连接类。 It will return the same instance everytime get() is called. 每次调用get()时,它将返回相同的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM