Android MVP that survives view life-cycle, configuration & internet changes, part-2
MVP + Clean architecture + RxJava, a combination which has successfully proven the test of time and its here to stay for a while. If you are already using this approach or planning to adapt it soon, here is the question worth asking, How to design an MVP that,
- Survives life-cycle changes of the view, Part-1
- Survives configuration changes
- Survives internet connection changes
I came across multiple ways to solve these issues. After some experiments and discussions, I finalised a combination of concepts which collectively solves these survival problems for my requirements. Here is a simplified sequence diagram, which we will discuss in detail.
There are multiple ways a presenter can survive configuration changes,
- Persisting the presenter in a presenter pool and retrieving it
- Using loaders to store the state of the presenter and retrieving it
- Using libraries like Nucleus
- Save the state of the presenter in bundle and retrieving it
All above listed solutions are good solutions and works well, you can use any of the above listed solution if required, instead of the solution we will discuss here, which is,
Use Fragment as View and use setRetainInstance(true)
Inject Presenter in the Fragment using Dagger with Fragment scope
Use setData() and loadData() methods to retain the View state
Note: This approach only works with Fragments.
Lets looks at some code, A sample fragment looks like this,
And a corresponding Presenter looks like this,
Internet connection changes
The third issue here is, how to design a smart Presenter which follows this flow chart.
To achieve this behaviour, here is a proposed solution,
Subscribe to internetConnectionSubscription when no internet connection is available and no data to load the view.
Unsubscribe to internetConnectionSubscription when we get the internet connection and load the data or on onDestroy()
This approach enables our presenter to wait for the internet connection as long as the view is alive, if needed.
Lets look at the code, a sample Presenter looks like this,
And a corresponding internet connection utility looks like this,
Use fragment as view, with setRetainInstance(true), inject presenter using dagger with fragment scope.
subscribe to internet connection subscription to wait for the connection and unsubscribe when we get the data or on onDestroy().
Complete Source Code
Complete source code is available on GitHub.
A set of use case specific code examples are available Here.