I've been working on Android for 9 months now from a server-side background where full unit testing and layered architectures are common and work well.
Through lots of trial and error and I would strongly suggest using the Model View Presenter
pattern, not Model View Controller.
A huge issue I've found is that Activities
/Fragments
have a lifecycle which is outside your control and can lead to unexpected issues.
For example, our main android app wants to be used in landscape mode on tablets. We do this in OnCreateView()
or OnCreate()
.
On a Nexus 7, the default view is portrait so what happens is that it starts the activity in portrait mode, our code then says go to landscape and android ultimately creates the activity
class 3 times!
We've hooked up network requests to onCreate
and they end up happening 3 times in this case.
Sure, we can add logic to look for duplicate calls but, in my opinion, it would be better, architecturally to try and divide the UI from the business logic.
My recommendation would be to use the factory pattern to create presenters from the activity but make sure the factory only ever returns the same instance. The presenter can then contain logic to do network request, look for duplicates and return cached results and general business logic.
When results from network calls return, either post to a bus such as Otto which the activity (register for the event on onResume()
and deregister during onPause()
) has registered to, or make sure the callback interface implemented by the activity has been updated to the last activity in the presenter.
This way, code in the presenter
downwards is unit testable and not reliant on flaky UI layer testing.