我正在尝试设置MVP应用程序,我想将交互器注入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
}
}
最佳答案
您可以将交互器传递到presenter的构造函数中:
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