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

标签 java android mvp

我正在尝试设置一个 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/

相关文章:

android - Android 上的嵌套 MVP : how to

java - 调用类构造函数和使用 Class.forName().newInstance 的区别

java - 如何使用数据库中的数据填充 ListView

java - 读取文件时忽略新行

java - android 类 fragment 膨胀时出错

delphi - 从 Delphi 项目中删除单例实例

java - 使用 Scanner 从打包的 jar 中读取大文件作为资源时出现 NullPointer

java - 将应用主题设置为 Material Design 并使用 Material 按钮后,布局预览不可见

android - 如何在 firebase android 应用程序中分离两个不同的用户?

asp.net - EF 模型和代码使用者之间存储库的使用