Lifecycle Observer

 1. Make DessertTimer a LifecycleObserver:

In order to achieve this, DessertTimer should implement a LifecycleObserver, take in a Lifecycle as a parameter and establish observer relationship in init block.

class DessertTimer(lifecycle: Lifecycle) : LifecycleObserver {
    init {
        lifecycle.addObserver(this)
    }
}

2. Annotate startTimer and stopTimer with @OnLifecycleEvent and the correct event:

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun startTimer() {...}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stopTimer() {...}

3. Pass in 'this' MainActivity's lifecycle so that it is observed:

dessertTimer = DessertTimer(this.lifecycle)

If you want to start at this step, you can download this exercise code from: Step.04-Exercise-Add-the-lifecycle-library.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Comments