LifeCycle Library
Want to learn more about the lifecycle library? Check out the Google I/O talks introducing the library:
Note these talks go far beyond what we cover in the lesson and into the topics of lesson 5 and lesson 6. For just an introduction to using Lifecycle, LifecycleOwner and Lifecycle observation, check out the Handling Lifecycles with Lifecycle-Aware Components Documentation
Now it’s your turn to complete this exercise yourself.
You're going to use Lifecycle Observation to start and stop the timer.
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.
Once you’re done, you can check your solution against the solution we’ve provided here Step.04-Solution-Add-the-lifecycle-library or using this git diff
Comments
Post a Comment