How to get context in moxy presenter android

1.4k Views Asked by At

How do I can get activity context from Moxy presenter? At first sight it's very easy...: 1. Add Context getMvpActivity (); into MvpView interface and implement it in Acivity. 2. And in a presenter call getViewState().getMvpActivity().

But Moxy don't allow to add the non-void methods to MvpView interface. Pls help me.

P.S. I need context in the Presenter to init App Component(activity is a param for static getter).

Thanks. Sorry for some grammar mistakes.

2

There are 2 best solutions below

3
senneco On BEST ANSWER

Right solution is not using activity context in the presenter. Because, in case of activity recreation, this context will leak (because presenter will be still alive). You able to use application context. You can pass it through presenter's constructor.

0
picKit On

Solved this problem with adding a Activity context as a param into onViewCreated(). Like this:

//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);
}