Skip to content
This repository has been archived by the owner on Mar 1, 2021. It is now read-only.

Presenter

Niek Haarman edited this page Oct 25, 2015 · 5 revisions

The Presenter is the class that handles logic and passes data to the View via the Container interface.

Lifecycle

A Presenter instance is a singleton instance in its screen scope, meaning it will survive events such as orientation changes. It can thus be used for both the portrait and landscape views. The lifecycle of the Presenter consists of only two methods:

  • onControlGained(Container, ActivityComponent) - When the View is attached to the window;
  • onControlLost() - When the View has gone away.

The Container

The Presenter communicates with the View using the Container interface. It is therefore possible to create two separate View classes for portrait and landscape, managed by one and the same Presenter instance. Optionally, you can use the View directly instead of the interace, but best practices suggest you use an interface.

You can get a hold of the Container using container(), which returns an Optional instance similar to Guava's Optional. This instance contains a reference to the Container if and only if it is called between onControlGained(...) and onControlLost(). It is therefore wise to check whether container().isPresent() returns true, before accessing the instance with container().get().

Counter example

A simple Presenter class which keeps track of a counter is given below:

class CounterPresenter extends Presenter<MyContainer, ActivityComponent> {

  private int mCounter;

  MyPresenter() {
    mCounter = 0;
  }

  @Override
  public void onControlGained(@NonNull MyContainer container, @NonNull ActivityComponent activityComponent) {
    container.setCounterText(String.valueOf(mCounter));
  }

  public void onIncrementButtonClicked() {
    if (!container().isPresent()) {
      /* Fail-safe return. */
      return;
    }

    mCounter++;
    container().get().setCounterText(String.valueOf(mCounter));
  }
}
Clone this wiki locally