gpt4 book ai didi

java - Dagger2 将交互器注入(inject)我的 Presenter

转载 作者:行者123 更新时间:2023-11-30 00:38:41 26 4
gpt4 key购买 nike

我正在尝试设置一个 MVP 应用程序,我想将我的交互器注入(inject) Presenter 类而不是使用 new 关键字。

参见下面的示例:

//演示者实现示例

public class ExamplePresenterImpl implements ExamplePresenter{

private final Application application;
private ExampleView exampleView;
private ExampleInteractorImpl interactor;

public ExamplePresenterImpl(Application application){
this.application = application;
// I WANT TO GET RID OF THIS AND INJECT INSTEAD.
interactor = new ExampleInteractorImpl(application);
}

@Override
public void setView(ExampleView exampleView){
this.exampleView = exampleView;
}

public void callInteractorMethod(){
// call Fetch method from Interactor
interactor.fetchData();
}

}

//交互器

public class ExampleInteractorImpl implements ExampleInteractor { 

private final Application application;

public ExamplePresenterImpl(Application application){
this.application = application;
}

public List<String> fetchData(){
// return value to the called function
}

}

最佳答案

您可以将交互器传递给演示者的构造函数:

public class MyPresenterImpl implements MyPresenter {
private MyView view;
private MyInteractor interactor;

public MyPresenterImpl(MyView view, MyInteractor interactor) {
this.view = view;
this.interactor = interactor;
}
}

然后在你的模块中:

@Singleton @Provides
public MyInteractor provideMyInteractor(Dependencies...){
return new MyInteractorImpl(your_dependencies);
}

@Singleton @Provides
public MyPresenter provideMyPresenter(MyView view, MyInteractor interactor){
return new MyPresenterImpl(view, interactor);
}

或者您可以使用 @Inject 注释对 Presenter 和 Interactor 构造函数进行注释。

我做了一个简单的登录页面的例子,有需要的可以看看:

https://github.com/omaflak/Dagger2-MVP

关于java - Dagger2 将交互器注入(inject)我的 Presenter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42930729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com