我正在尝试设置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
}
}
答案 0 :(得分:1)
您可以将交互器传递给演示者的构造函数:
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构造函数。
我用一个简单的登录页面做了一个例子,如果你需要,你可以看看它:
答案 1 :(得分:0)
您应该将Presenter注入View(例如Activity)类。创建一个类似ExampleModule的模块和一个像ExampleComponent这样的组件,它将提供演示者。 Presenter应该有一个构造函数,它需要所有需要的依赖项。在此示例中,依赖项是Application和交互器