Anyone who’s starting to learn about Android development says lifecycle activities and fragments are a mystery.

As a reminder, here is the life cycle of the activities:

And that of the fragments is similar though a bit more complicated:

So, when we want somewhere in our code to perform an action when the activity is paused, for example, we must start the activity, overload the pause method, and perform this action, for example:

And if we want to relaunch it at the time of the onResume, and the binder at the rest of the life cycle:

But let’s imagine now that our object rentalManager is contained in another object, for example, a Presenter, it would be necessary:
– To overload each method of our life cycle in our activity 
– To create for each method its equivalent in presenting it 
– In each of the methods of the presenter, connect it to that of the locationManager

We are therefore creating a multitude of useless methods.

Android Component Architecture: Lifecycle

Our friends at Google have redesigned this problem and offered us a solution: the Lifecycle !

It is now possible to recover in our activities and fragments a Lifecycleobject to which we can add listeners, and be notified of the change of state of our component.

For example, we can ask to be notified when the activity pauses, since our presentation, without the activity having to call a pause method of our present.

1. Installation

To take advantage of the architecture’s components, nothing simpler, use a version of appcompat-v7 greater than 26.1.0

And use the fragments of the v4, as well as the AppCompatActivity (or FragmentActivity)

2. Use

Its use is very simple, on your Activity / Fragment, get the Lifecycle object with the getLifeCycle () method, then give it to the object that needs to be warned of the changes of states

There you go! I do not know about you but I can not do without this beautiful bookstore!
It allows you to cut the code by avoiding having to add to all our objects methods to share the life cycle everywhere, and it makes the code very clean.