如何在Moxy Presenter Android中获取上下文(Context)

4
我怎样才能从Moxy presenter获取活动上下文? 乍一看似乎很容易...:1.在 MvpView 接口中添加 Context getMvpActivity(); 并在Activity中实现它。 2.在 presenter 中调用 getViewState()。getMvpActivity()
但是,Moxy不允许将非void方法添加到 MvpView 界面中。 请帮帮我。
附言:我需要在Presenter中使用上下文来初始化App组件(activity是静态getter的参数)。
谢谢。 抱歉有些语法错误。
2个回答

6

正确的解决方案是不在Presenter中使用Activity的上下文。因为在Activity重新创建时,这个上下文会泄漏(因为Presenter仍然存在)。您可以使用应用程序上下文,并通过Presenter的构造函数传递它。


我认为我不能使用应用程序上下文。因为getApplicatin()方法只能使用活动上下文。 - picKit
在进行 DI 组件注入之后,我可以使上下文为空...我不想跟你谈论 Moxy 库...请阅读关于 Moxy 中 ViewState 的文档...它是如何工作的。 - picKit
1
如果您在注入后清除上下文,它仍可能会发生上下文泄漏。因为一些被注入的组件将处理此上下文链接。如果需要应用程序,请提供Application而不是Context。此外,我建议像这样直接在Presenter的构造函数中提供依赖项:https://github.com/Arello-Mobile/Moxy/issues/100。PS:我对moxy视图状态非常了解;) - senneco

0

通过将Activity上下文作为参数添加到onViewCreated()中,解决了这个问题。 像这样:

//presenter super class
public void onViewCreated (Activity activity) {
    //init component here
    //this.component = ...
    injectPresenter ();
}

protected PresenterComponent getComponent () {
    return this.component;
}

protected abstract void injectPresenter ();



//presenter child class
@Override
public void onViewCreated (Activity activity) {
    super.onViewCreated(this);
}

@Override
protected void injectPresenter () {
    //you can name "inject" different ways
    //in your presenter component interface
    getComponent().inject(this);
}



//activity class
@Override
protected void onCreate () {
    //P.S.(for beginners) variable presenter is the object of class
    //which extends Presenter super class
    presenter.onViewCreated(this);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接