Modeling my presentation layer

  9 mins read

After modeling my domain layer here it comes, modeling my presentation layer. The reason for this post is that I saw in many projects that are moving from a legacy codebase to an MVP approach that there are some issues trying to differentiate what belongs to the presentation layer and what belongs to the UI layer. In my previous project, I saw also a comment that was telling: “I cannot grave in a stone what is a business rule”. This is very bad if you are not able to recognize what belongs to your domain you are going to make mistakes while you separate the responsibilities. Why are you trying to make a Clean approach without knowing the very basics?

I’m going to give you some examples and how I solved it. This article is more about to get the concepts clear, the implementation is not really important, you can achieve it in many ways.

Android view vs View vs Screen

  • Android view: Just an Android component, something that extends from android.view.View
  • View: The view interface to communicate from your presenter to your view implementation, it can be implemented in your preferred Android component, sometimes is better to use an Activity others a Fragment or maybe a Custom View.
  • Screen: A screen is more a user concept, the user gets the feeling that the phone is navigating between windows, but we can represent this in Android with Activities or replacing fragments/views in the same Activity. So it depends on the perception that the user gets and usually represents all the content that you can see in the view.

Navigation to a different screen

A navigation between two screens can be between two fragments, two activities, open a dialog, open an activity, etc… How this is achieved is an implementation detail, and is the responsibility of our delivery mechanism. But what about the action to navigate from a screen to another? That action is the responsibility of our presentation layer. Our presenter should know about what to do and our implementation how to do it. In this case: What to do? To navigate to another screen and how to do it? Open a new Activity. Then, we have a problem, as I said before my presentation is pure java, so I can’t use any android related stuff in my presenter, how to achieve this? Using an abstraction. You can create an interface called NavigationCommand with a simple method navigate() and call that method when is needed from our presenter and implement this interface in our Android module. Assuming that we have Activity A that wants to navigate to Activity B when a button is clicked, here is the sequence of how it will work:


The code will look like:

Android module (View layer)

public class ActivityA extends Activity {
 public void onSomeButtonClicked() {
public class ToActivityB implements NavigationCommand {
  private final Activity currentActivity;

  public ToActivityB(Activity activity) {
     currentActivity = activity;

  public void navigate() {

Java module (Presentation layer)

public interface NavigationCommand {
 public void navigate();
public class PresenterA {
 private final NavigationCommand toBNavigation;

 public PresenterA(NavigationCommand toBNavigation) {
    this.toBNavigation = toBNavigation;

 public void onSomeButtonClicked() {

With this approach, we are decoupling responsibilities between different layers. We extracted the navigation to a class that we can reuse everywhere in our project to navigate to our Activity B. We can test our presenter to invoke the navigation command and if we change the way of displaying that screens (from Activities to Fragments for ex) our presentation layer will not change. Long live to the Open close principle!

Another problem that I faced is when you have two or more Navigation Commands in the same presenter, the parameters to construct that presenter can become weird:

public class PresenterA {
 private final NavigationCommand toBNavigation;
 private final NavigationCommand toCNavigation;

 public PresenterA(NavigationCommand toBNavigation, NavigationCommand toCNavigation) {
    this.toBNavigation = toBNavigation;
    this.toCNavigation = toCNavigation;

For the client that instantiates this presenter is hard to know the order of the navigation commands, you only can rely on the name. But we can have another interface to inherit from NavigationCommand to represent that subtype of Navigation. Another solution if you are using dependency injection can it be to implement a Qualifier to specify which type of parameter you need to pass.

There are some cases where you will need to navigate with a parameter to the screen A to the screen B, then we can modify our NavigationCommand to represent the dependencies that we need to navigate:

public interface ToScreenBNavigationCommand extends NavigationCommand {
 void setMyParameterToNavigate(String parameter);

If we do that, we can use that method from our presenter before call navigate() to set up our navigation.

Credits of this idea goes to Pedro who has implemented this in his project EffetiveAndroidUI

More than one View in the same screen

There are many Android components that can be view elements, it does not matter for our Presenters. Remember that a View is like a contract that our presenters work with. Can we have more than 1 view on the same screen? For sure yes! How I can have more than 1 view/presenter in one Activity? Well, let’s consider the Browse Spotify’s screen for this example:

Spotify app

In my way to see this screen we have a horizontal slider with different playlists, then we have a menu with some options available in this browse music concept and at the bottom, we have the current playing song. In this screen, we clearly have different concepts and in my way to see how this screen works, the concepts are not related to each other, so let’s consider to have a view/presenter for every concept that we talked about:


  • RecommendedPlaylists View/Presenter
  • BrowseMenu View/Presenter
  • CurrentPlayingSong View/Presenter

So why to create that structure, it is not the same to create one Presenter to have all the actions and some custom views? Think who is the responsible for fulfilling that views and if you want to reuse that component how you will achieve that. Probably RecommendedPlayLists is hitting the network to get the recommended playlist for the current user, it does not make sense if we create a custom view group with a presenter in order to achieve that? It can be reused everywhere. What about the browse menu? this is another concept of the view, it is just a menu that when you hit an item it will navigate to another screen (using a navigation command!). And finally, the current playing song that for sure it will be reused in other places.

As you can see a screen can have more than one View / Presenter because a screen can be a summary of other things and can have more than one responsibility, this thing really depends on the design. (Remember that a responsibility is a “reason to change”, and each of these views could change for several reasons)

Can we have 2 implementations for the same view?

Yes! we can have multiple implementations for the same presenter view, for example in the Spotify app, the screen that I have shown you has a view that controls the current song and displays the song information, but if we click in that view we get:

current playing song

It is not the same but with a different way to show it? So maybe we can reuse the same presenter and re-implement the view interface in a different Android component. But, this screen seems to have some extra functions, would you put those new functions in the same presenter? It depends on the case you have multiple alternatives: you can compose a presenter with different actions, use two different presenters one for the actions and other for the presentation, or simply have one presenter with all the actions because it represents the same concept. Remember that there is no perfect solution, software is about trade-offs.

But, it’s fair to say that this is not a common case, usually, a Presenter has only 1 view implementation.

MVP composition

To summarize what we have seen so far:

  • A view uses 1 presenter
  • A screen can have 1-n views/presenters
  • A view can be re-implemented 1-n times to use with the same presenter
  • An Android component can implement 1 view. If you are implementing 2 view interfaces, maybe is because those two views are better to be together as a whole concept or you need to separate the view implementations in two separate android views

Let’s move forward to other key concepts:

Presenter lifecycle

The following screenshot is from Citymapper, when you hit the “Get me somewhere” button opens a screen where you can choose the start and end positions of your trip:


How will you decompose this screen? The first thing that comes into my mind is: Does the concept of start location make sense without an end location? I don’t think so, I would create one presenter “PickLocation” that knows about when the start and end locations are filled. An activity with 2 fragments in a view pager should do the job in the view layer, both fragments can access the same presenter and call “presenter.startLocationChanged()” and “presenter.endLocationChanged()”.

What if the design changes and now instead of having 2 tabs, we decide that is better to navigate like 2-steps form?Then we have to replace the start location fragment with the end location fragment. Our view layer should change, but our presenter will be the same. In addition, we can think about having 2 maps on the same screen one at the top with the start location and another at the bottom, is the same example as before, our view implementation changes but not our presenter.

So what is the lifecycle of my presenters? It depends on the component(s) that we need to represent with that presenter.

To explain that, let’s take a look at the Selltag app, a second-hand application. This is how we used to create products in that application:

New product - step 1New product - step 2New product - Step 3

As you can see is a 3 steps form. Despite the Spanish words, I think is clear enough, “Siguiente” is “Next” and “Publicar” is “Publish”.

In the first step, you create some pictures of the product, the second step is to fill the title, description, and price, lastly, you hit the publish button and the product will be published.

My way to model that form is with one presenter again, a “PublishProductPresenter”. This presenter represents a whole concept “Publish a product”. How will it look on a tablet? Maybe the 3 steps are together because you have an ample screen. And what about a web application? Will it be another approach just because at the first moment you see different designs? We are only changing the view layer, but our presentation layer should be the same because it reacts to the user events and makes queries to our domain.

But, hey! I can split it into 3 presenters and use it, in the same way, you are using your whole presenter. Ok, maybe you are right, but how are you going to send the information from the first steps to the last one who is the responsible for creating the product? Are you going to have a reference of a presenter inside another presenter? Maybe are you going to create a shared object for all those three presenters and change the properties in every step? It sounds dangerous and hard to debug if you have any bugs.

You can create this 3 screens as an Activity with 3 fragments that will be replaced or 3 different activities.

Presenter state

What about orientation changes? Your activity will be destroyed and your presenter too. Most of the problems that I saw regarding if a presenter has to be stateful or not belongs to the domain layer. I’ll explain it with the next example:


This is F-Droid for Android, an alternative and open source market that only contains open source applications. That Available apps are refreshed making a network request. Imagine that if we rotate the screen and our presenter is stateless then the list will be reloaded. How can you solve it? Well, the question is actually pretty simple you can create a temporal in-memory or disk cache to save the previous response and invalidate it with a TTL (time to live). But never store the items that you received from the network in your presenter, because if you need to recreate your presenter, then you will have the problem that you need to keep the reference to those items in order to don’t make that request again. So in summary, I always try to make my presenters stateless.

Callback hell

Callback hell is one of the most discussed topics when people talk about the presentation layer. Many of the problems that I saw related to that callback hell are again because we are letting the presenters do too much. Remember that is not the responsibility of the presentation layer to coordinate actions of our domain. Our presentation layer should call the actions of our domain and those actions are the ones that handle that synchronization, leaving our presentation layer simple. You can see this action modeling in my previous post modeling my domain layer. Before integrating libraries such as RxJava or Jdeferred think if you need that tools or you are making some design mistakes and that tools are the only option to glue that parts of your system.

To illustrate it I’ve created an example. Imagine a system where you only have to show a list of products if some flag retrieved from a server is true. This frist approach should be wrong mainly for 2 causes, the first one is that your presenter doesn’t need to know about this flag thing because is something related to our domain. The second cause is that this bad coordination is making us write more lines of code in our presentation and deal with the synchronization things:

callback hell

Instead of coordinating those things in the presenter, we can do the following:

proper domain

As you can see, now we don’t have any problems and the action that we are calling is clear enough. In addition, if this flag is not needed in a feature the only point that I need to change is my action.


Model our presentation layer is very easy, but you have to be sure what belongs to that layer and what is the responsibility of the domain. When you have a huge presenter, ask yourself if it is really a huge screen with a lot of user events to handle or you have another problems like that your presenter is doing some domain actions, etc…

Written by:

Christian Panadero Martinez

  • Pablo Baldez

    to handle imageviews transactions between activities we need to pass an imageview as parameter. So, the presenter should to know about imageview class to send it to your navigation pattern. It’s a necessary antipattern or do you have another approach?

    • Hi pablo, it’s not necessary at all. The navigation command has the activity to get the context and navigate and you can do a findViewById and set up everything inside the navigation command.

  • lenguyenthanh

    Thank you so much for this great post. I have a question Presenter Lifecycle section. When you talk about Selltag app, you use a presenter for 3 screens, which may equal to 3 views. So that this presenter has 3 views? Does my understanding correct? And how you implement it?

    • In this case, you have 2 options:
      – 1 presenter, 1 view: If you think how you will represent this on a tablet, all can fit in the same screen, so if it is a mobile and you want to re-use the presenter/view interfaces that you already have is not a bad idea to have 1 view interface.
      – 3 presenters, 3 views: What I told in the post.

      The option with a single presenter and 3 views is not considered by the specification of the pattern, but if it helps your case, it can be a solution.

      • lenguyenthanh

        Thanks for your answer, but I still have a question for the first option. On tablet we have 1 presenter, 1 view it is really obvious. But when it is on mobile, it will be 3 screens. So 3 screens need to be composed as 1 view? Could you please explain more on this situation? Thanks!

        • What I’m proposing is to have 1 activity and 3 fragments. That fragments in this case does not need to have a presenter, I consider it more like a custom view. You can inject the same presenter in every fragment that composes that screen. If you do that, you will have the same presenter for a tablet/phone and you will avoid the problem while communicating presenters. What do you think?
          Thanks for your comments.

          • lenguyenthanh

            Using 1 presenter and inject it to each view is really cools. I think it will be the best way for this situation.

            Thanks again!

          • Andrew Gibel

            I use this pattern whenever I have a ViewPager with Fragments. After trying a few different methods, I find that injecting the base Fragment or Activity presenter (the one that holds the ViewPager) and using it directly works the best. However, I start running into the problem of having very large presenters since they are handling the duties of n distinct screens.

  • Pingback: Issue #193 - IT大道()

  • Pingback: Android Weekly - 第 193 期 - IT大道()

  • Andrew Gibel

    One of the more interesting things you do here is the Strategy Pattern with the NavigationCommand. I have always done the implementation of View actions back in the View itself. For instance, in the nav case I called ActivityA->PresentarA->ActivityA.navigate(). Do you limit the use of this pattern to navigation or do you use similar independent Actor delegation for all actions the presenter would like to perform in the view?

    • Actually I’m using it only for navigate, but the main goal is to leave the presenter without any dependency to the android framework, so in case that you need to decouple something it can be a nice strategy.

  • neoranga

    Nice article, thanks for sharing.
    I have a question about the deadly lifecyle and the state: Imagine that list in F-Droid is not loaded automatically when you open the activity but when user presses the “refresh” button, while it’s refreshing the user decides to rotate and the activity is recreated. In this scenario the network call finishes correctly in the background but the question is, would you save the state of the view (loading)? Where would you save it so you don’t loose the results?

    • This is more a domain question rather than a presentation thing. That is why I try to keep my presenter stateless, to don’t deal with that problem in my delivery mechanism. Instead, consider keeping a cache global or scoped to your activity lifecycle in your domain layer. Doing that, your presenter will call an interactor every time you reach let’s say, onResume. But it will not hit the network, only your local storage.

      • neoranga

        The question is more related to how to keep the loading state of the view after rotation. Since this loading doesn’t happen until the user presses the “refresh” button the UI should be first in one state -static- and then in another -loading animation- until the model notifies the results. In the case where the activity is recreated after rotation, how does the view and the presenter know what to show on creation? Does the presenter ask on creation if there is any ongoing work in the model to change the state of the view? Or would you store the state of the view with Android’s onSaveInstance() and restore it in the presenter?

  • eoin

    theres a lot of good information here to study. thanks. i still hve issues with mvp. Like sometimes creating a pretty bloated model class. how do you create the command class. do you just instantiate it in your activity then pass it as a parameter to the presenters constuctor. thanks

    • Hi eoin, if you use dagger, in your modules. If you are not using any DI you can use a service locator pattern or whatever that helps you resolving dependencies. Then with the dependency created send the instance to your presenter by constructor so you can mock it for your tests.

      • eoin

        yeah i use dagger 2. so you inject the navigationcommand into the ‘view’? i presume you inject your presenter aswell? Ill study the project on github. ive also been looking at israel ferrer camacho’s github. he has a nice implementation of MVP
        . thanks again!

  • Sebastian Pareyro

    Hello Christian, thank you for this post. Could you explain where to save state of product creation (Selltag app example) if it would be implemented with 3 fragments and 1 presenter

    • Yes, in that case I would keep the state in the presenter, because saving the fields in the view will keep things more complicated 😉

      • Sebastian Pareyro

        So I should inject presenter to activity and use fragments just as views? Doesn’t it complicate an interaction activity with views inside fragments?

        • It should not, you can inject the presenter in the activity and fragments to control the events. If a fragment is part of the composed view, you should have a presenter to handle the views. If you were using custom views inside the activity instead of fragments maybe it will be easier to handle if you want to inject the presenter only once.

          • Sebastian Pareyro

            And should I have one presenter for activity and presenters for each fragment, those would interact with activity presenter? Or you mean another scheme?

  • Dominic Cheng

    Learned a lot! Is it ok that I translate it into Chinese and post it on my own blog? It’s only for sharing this knowledge, no commercial intentions. I will leave a link back to this page at the beginning, of course. Thanks!

    • No problem, if you keep a reference to the author and the link to this page is fine 🙂

  • Pingback: 如何设计MVP中的Presentation层 丨 程大治()

  • matias

    Sorry for make the question in Spanish:

    Christian tengo una duda, imaginate que vos tenes un combo con informacion que precargas de tu capa de dominio y en base a lo seleccionado mostras un tipo de view u otro (en la misma pantalla).

    Luego de un cambio de configuracion (ej rotas el dispositivo), como podrias mantener el estado de la UI con un presenter stateless?

    • Hola Matias, recuerda que porque la pantalla rote no tiene porque recrearse, solo si tienes diferentes layouts, revisa los configChanges si no sabes de lo que hablo. Si fuera el caso en el que necesitaras que se recrease, mi capa de dominio me da lo ultimo que tenga ya que usa internamente una cache local que solo vive durante el ciclo de vida de mi activity. Si aún así no te soluciona el problema, tu presenter puede vivir durante todos los cambios de orientacion reteniendolo en el getCustomNonConfigurationChange aunque si fuera stateless deberia de pertenecer, hay veces que no queda mas remedio.

  • Pingback: L’architecture MVP | Jonathan Pannetier()

  • Pingback: Model-View-Presenter(MVP) Definitions and Best Practices – Thanh Le Codes()

  • Bacillus Bulgaricus

    It feels something wrong with setMyParameterToNavigate(). Imagine how it can be implemented by an activity. Will pollute the activity with parameter variables. To deal with this I guess ToScreenBNavigationCommand needs to be a class like in +pedrovgs project not an interface. 1 navigation target will have 1 navigation command in order to be navigated to. The command will know the target UI structure so it could get the fragment manager, search for a “detail” fragment and if it’s present and decide if to start new activity or show in the “detail” fragment. Hmm, I don’t know if that is not considered a presentation logic!?

    • Nobody has said here to implement a NavigationCommand in an activity/fragment, if you do that you are losing the whole point and does not make any differente to just add some methods in your mvp view interface. Navigation command must be a different class. About the responsibility that you mention, the intention of navigate is presentation logic but the way that you implement that navigation is framework related. I know that sometimes is hard to deal with `Context` and some other framework specific classes, but this should abstracted in a pure implementation.

      • Bacillus Bulgaricus

        Oh, my bad! 😀 I’ve assumed (maybe it’s time for me to get glasses) ToActivityB is an activity class but it’s not! Now is more clear.
        10x for the assistance, very nice blog!

  • Pingback: Android MVP 详解(下) | android学习贴士()

  • Pablo Baldez

    Using this navigationcomponent as pattern, how did you do to get the results when startActivityForResult is called? I can’t send the Intent to presenter because this presenter is Java only, but this way I can’t extract the result defined in setResult method. What is the best approach?

  • Pingback: Android MVP | 코딩을아는가()

  • eoin

    why is the navigationcommand implementation in the mainactivity in the application? as it seems to be done differently to the example you have here? its also not very generic seen as the destination activity is hard coded to the implementation and the attributes passed so its very specific to a certain activity, sending certain attributes in the intent. do I create an action command for every activity? this seems to violate DRY. cheers!

    • Hey eoin, the navigation command shouldn’t be implemented in any activity, where have you seen that?

      And yes, you should separate the navigation from the presentation, those are 2 different concerns. DRY is don’t repeat, but you are not repeating anything, the navigation to activity is different to another activity.

      • eoin its in here. thanks for the pointers. I need these things to be clear in my mind. I really like the Idea of the navigation command, I haven’t used it previously. I am reworking some legacy code and I am hoping to use it this time.

        • Hey eoin, now I understand what you mean, yep, sure that was an old approach, as you could notice by the date of the commit. The way should be as I described in this post. The reason is mainly separation of concerns, the UI shouldn’t be responsible for navigation, that is a presentation concern. but even if you do it in that manner, is something since you are separating it in a class and you don’t have that logic in the UI.