Creating your own lifecycle-aware component
We need to make our CustomCountdown
aware of the lifecycle of MainActivity
. In other words, our countdown logic should observe and react to the lifecycle events of our LifecycleOwner
– that is, MainActivity
.
To make our CustomCountdown
lifecycle-aware, we must force it to implement the DefaultLifecycleObserver
interface. By doing so, the CustomCountdown
will be observing the lifecycle events or states defined by the Lifecycle
object that LifecycleOwner
provides.
Our main goal is to pause the countdown when the app is put in the background and to resume it when the app is brought back into the foreground. More precisely, our CustomCountdown
must react to the following lifecycle events of MainActivity
:
onPause()
: When theonPause()
callback comes inMainActivity
,CustomCountdown
must pause its countdown.onResume()
: When theonResume()
callback comes inMainActivity
,CustomCountdown
must resume its countdown.