【问题标题】:How can inject Model to Presenter when create it wit dagger2?使用匕首 2 创建模型时如何将模型注入演示者?
【发布时间】:2017-12-27 09:43:39
【问题描述】:

我尝试创建MVP + dagger2

我创建模型 moudule:

@Module
class ModelsModule {

    @Provides
    BasketModel provideBasketModel() {
        return new BasketModel();
    }

    @Provides
    ProductModel provideProductModel() {
        return new ProductModel();
    }
}

我需要创建演示者。我的演示者必须使用模型

演讲者:

public class ProductPresenter {

    private ProductModel;

    public ProductPresenter(ProductModel productModel) {
        this.productModel = productModel;
    }

   publict void test(){
      productModel.someMethod();
     }

而且我在创建 Presenter 时无法设置 ProductModel。我这样创建的演示者:

@Module
public class PresentersModule {

    @Provides
    ProductPresenter provideProductPresenter() {
        return new ProductPresenter();//What I need set to constructor? new ProductModel()?
    }

【问题讨论】:

  • 你的组件在哪里?你是如何构建你的组件的?

标签: android dagger-2 android-mvp


【解决方案1】:

由于您在演示者类中传递 ProductModel,因此您还需要告诉您的 PresenterModule 如何构建演示者:

@Module
public class PresentersModule {

@Provides
ProductPresenter provideProductPresenter(ProductModel model) {
    return new ProductPresenter(model);
    }
}

Dagger 足够聪明,可以发现您已经在另一个 @Module 类中构建了模型实例。

我认为您还需要使用 @Inject 注释您的 Presenter 的构造函数:

@Inject
public ProductPresenter(ProductModel productModel) {
    this.productModel = productModel;
}

编辑:显然你需要一个@Component 接口。你还没有发布任何相关的代码,但我假设你有一个。

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 2021-10-20
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多