Hi Ruslan,
Antonio Gutierrez
41

Thank you for your remark, Antonio.

You are right, injecting Presenters in onCreate() is not correct as we don’t want to instantiate presenter on rotation, so Lazy<T> (or Provider<T> as it comes with Dagger2) should be used instead. I experimented with passing a Provider<P> to onCreateLoader() callback, and then call its get() method in onForceLoad(), and it works very well. It also gives a great advantage: you can inject Provider<P> as a field of base PresenterActivity<P, V> class and keep your child Activity very clean.

But this will work only until you need to pass special parameters to Presenter instance from a Fragment or Activity class, so I went back to factories, but good news here is that factory can also get a Provider<P> instance injected via constructor injection. In factory’s createPresenter() method I get Presenter instance by calling presenterProvider.get() and initialize it before returning to Loader.

So my current scheme is:

  1. Activity gets PresenterFactory injected as a field.
  2. PresenterFactory gets PresenterProvider injected into constructor.
  3. In getPresenterFactory() method of Activity I pass my params into factory.
  4. In createPresenter() method of factory, which is called in onForceLoad() method of Loader, I get Presenter’s instance from Provider and pass params to it.
Show your support

Clapping shows how much you appreciated Ruslan Arslanov’s story.