Observing a Lifecycle

Most likely, if you are interested in the Architecture Components, you are up to speed with Java 8 and are interested in using it in your project. In that case, you can go the preferred route and use DefaultLifecycleObserver as your observer implementation. This takes advantage of Java 8’s ability to define methods on interfaces, so that you only need to override the particular lifecycle events that concern you.

So, for example, here is an observer that passes all events to a RecyclerView.Adapter named EventLogAdapter:

  static class LObserver implements DefaultLifecycleObserver {
    private final EventLogAdapter adapter;

    LObserver(EventLogAdapter adapter) {
      this.adapter=adapter;
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
      adapter.add("ON_CREATE");
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
      adapter.add("ON_START");
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
      adapter.add("ON_RESUME");
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
      adapter.add("ON_PAUSE");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
      adapter.add("ON_STOP");
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
      adapter.add("ON_DESTROY");
    }
  }

In our case, we happen to pay attention to all of the events; that is not required.

Then, you can register the observer, and it will start being called for the various events:

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    setTitle(getString(R.string.title, hashCode()));

    RecyclerView rv=findViewById(R.id.transcript);

    adapter=new EventLogAdapter(getLastCustomNonConfigurationInstance());
    rv.setAdapter(adapter);

    getLifecycle().addObserver(new LObserver(adapter));
  }

All of this code is from the General/Lifecycle sample project, which shows you the events in a RecyclerView as they come in. The MainActivity handles configuration changes via onRetainCustomNonConfigurationInstance(), so you can see the lifecycle events across a configuration change. Through an overflow menu item, you can kick off another instance of MainActivity, then press BACK to see the flow of lifecycle events as the original instance comes and goes from the foreground.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.