4

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.

picKit
  • 412
  • 1
  • 4
  • 14

2 Answers2

6

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.

senneco
  • 1,786
  • 2
  • 12
  • 15
  • I think I can't use App Context. Because method getApplicatin() works only with activity context. – picKit Jun 09 '18 at 11:21
  • and after a DI component injection I can make context null... and I don't wanna talk u about the Moxy library... pls read about ViewState in moxy... how does it work. – picKit Jun 09 '18 at 21:48
  • 1
    If you clean context after injection, it may still activity context leak. Because come injected components will be handle this context link. If it's require Application, you can provide Application instead of Context. Also, I recommend to provide dependencies right in Presenter's consturctor like this way: https://github.com/Arello-Mobile/Moxy/issues/100 . PS: and I know all about moxy view states ;) – senneco Jun 13 '18 at 12:45
0

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);
}
picKit
  • 412
  • 1
  • 4
  • 14