MVP-5: The lifecycle of Presenters should follow the lifecycle of the Views, but not by replicating the complexity of the lifecycles of Android components.


Description

By having callbacks related to the Activity lifecycle in Presenters, Presenters become tightly coupled to Activities lifecycle. This can have a negative impact in terms of maintainability. From an architectural perspective, Presenters should not be responsible for data-related tasks. It is hence advised not to retain Presenters. An alternative solution would be to use a caching mechanism to retain data, keep Presenters stateless, and destroy Presenters when their corresponding Views are destroyed.

Example

We created a simple MVP login Application.

MVP event diagram:

Login Injection

After the login is successful, the AuthComponent gets added to the AppComponent. With the plusAuthComponent() method.

When the GreetActivity and the ViewUserActivity are created. Their respective component is being set up and added to the AuthComponent.

Our ViewUserPresenter has a one-to-one relationship with viewUsersView. This is injected when the ViewUserActivity is created.

Which is provided in our ViewUsersModule.

When the view is added to the module a new ViewPresenter is provided with this ViewUserView. When this view is removed the presenter is removed as well.

When the user logs out, the AuthComponent is removed with the corresponding presenter and view. The Presenter only has a reference to the view and not directly to the Activity. Dagger injects the Presenter in to the LoginActivity. Dagger also injects the LoginView in the Presenter.

Once the Activity is destroyed and eligible for garbage collection, so is the component and it’s dependencies, so memory leaks are avoided. Dagger performs the maintainability of Presenters.

Check out the Github page to view the complete repository.