gpt4 book ai didi

java - 带有 Android : How to inject context when using MVP? 的 Dagger

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:58 25 4
gpt4 key购买 nike

在开发 Android 应用程序时,我偶然发现了一个问题。我刚开始使用 Dagger,所以我知道一些基本概念,但是当在教程及其用例范围之外使用它时,事情就变得不太清楚了。

那么进入正题。在我的应用程序中,我使用了这篇博文中描述的 MVP:http://antonioleiva.com/mvp-android/

所以一开始我将 Interactor 类(处理数据的类)注入(inject) Presenter 类,一切正常。但是后来我实现了使用 SQLite 数据库的方法,所以现在需要在我的 Interactor 类中使用 Context。

我不知道该如何正确执行此操作?我的临时修复是从我的应用程序中排除 Dagger,并在创建 Presenter 类时在构造函数中传递 Context 变量,然后在 Presenter 中传递 Interactor 类,但我想使用 Dagger。

所以我当前的应用程序看起来有点像这样。

MyActivity implements MyView {     
MyPresenter p = new MyPresenter(this, getApplicationContext());
}

MyPresenter 中的构造函数

MyPresenter(MyView view, Context context) {
this.view = view;
MyInteractor i = new MyInteractor(context);
}

MyInteractor 的构造函数中,我将 Context 分配给一个私有(private)变量。

我只需要将 MyInteractor 注入(inject)到 MyPresenter 中,因为这是应用程序的一部分,需要针对不同的实现进行测试。但是,如果还可以将 MyPresenter 注入(inject)到 MyActivity 中,那就太好了 :)

我希望有人对我正在努力实现的目标有一些经验:)

最佳答案

在你的类 MyInteractor 中:

public class MyInteractor {

@Inject
public MyInteractor(Context context) {
// Do your stuff...
}
}

MyPresenter 类

public class MyPresenter {
@Inject
MyInteractor interactor;

public MyPresenter(MyView view) {
// Perform your injection. Depends on your dagger implementation, e.g.
OBJECTGRAPH.inject(this)
}
}

为了注入(inject)上下文,您需要编写一个带有提供方法的模块:

@Module (injects = {MyPresenter.class})
public class RootModule {
private Context context;

public RootModule(BaseApplication application) {
this.context = application.getApplicationContext();
}

@Provides
@Singleton
Context provideContext() {
return context;
}
}

将您的 Presenter 类注入(inject)到您的 Activity 中并不是那么容易,因为在您的构造函数中您有这个 MyView 参数,它不能被 Dagger 设置。您可以通过在 MyPresenter 类中提供 setMyView 方法而不是使用构造函数参数来重新考虑您的设计。

编辑:创建 RootModule

public class BaseApplication extends Application {
// Store Objectgraph as member attribute or use a Wrapper-class or...

@Override
public void onCreate() {
super.onCreate();
OBJECTGRAPH = ObjectGraph.create(getInjectionModule());
}

protected Object getInjectionModule() {
return new RootModule(this);
}
}

关于java - 带有 Android : How to inject context when using MVP? 的 Dagger ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29387188/

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