Well, these events actually belong to the enum Event. And this enum Event is a part of abstract class Lifecycle.
Similar, to enum Event we have enum State which we will talk about in the next episode.
Now, the values of this Event enum are as follows:
Starting with ON_CREATE through ON_DESTROY. You will also find a special enum value of ON_ANY which is applicable for all lifecycle events of a lifecycle owner. Fine?
Let’s explore how and when these events are actually triggered in context of Activity and Fragment lifecycle.
Right in front of you is a typical lifecycle of an Activity and a Fragment.
Now, as soon as the onCreate of Activity is executed, it dispatches an ON_CREATE event. When this event is dispatched, the observer which in our case was NetworkMonitor, will execute the overridden onCreate method inside it.Which we just saw in our demo. Right?
Similarly, after onStart, ON_START event is dispatched. Followed by onResume, ON_RESUME event is triggered.
The same applies for the Fragment as well. ON_CREATE, ON_START, and ON_RESUME events are triggered after each callback.
But please note that, after the execution of onCreateView and onViewCreated there is no event triggered. Fine?
Now, let’s come to destructive phase of the Activity’s lifecycle.
Before execution of onPause method, ON_PAUSE event is triggered. Similarly, before onStop and onDestroy, ON_STOP and ON_DESTROY event is dispatched. Quite simple isn’t it?
But here is a catch, during the constructive phase of Activity’s lifecycle, the events are dispatched after the execution of lifecyle methods. Such as after onCreate is executed completely then only ON_CREATE event is dispatched.
Similarly only after onStart has finished its execution ON_START event is triggered.
But in the destructive phase of Activity, if you notice, first the event ON_PAUSE is dispatched followed by this onPause method is executed. So here in this case first the event is triggered and then only the lifecycle callback is being called. So please note this. This is very important to remember. The difference between these two phases.
Now, for fragment as well, the events are dispatched before the lifecycle callbacks in the destructive phase of the Fragment lifecycle. Fine?
So I hope you have a got a clear picture of how and when the events are dispatched during an Activity’s and Fragment’s lifecycle. So yes, that’s all for this episode.