From the course: Android Development Essential Training: App Architecture with Kotlin

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Handle events with LifecycleObserver

Handle events with LifecycleObserver - Android Tutorial

From the course: Android Development Essential Training: App Architecture with Kotlin

Start my 1-month free trial

Handle events with LifecycleObserver

- [Instructor] I've previously shown how to handle activity lifecycle events with code in the activity. Google offers a more sophisticated approach to this task though using a class called a lifecycle observer. The goal is to slim down the activity and move code that reacts to life cycle events to a special class that doesn't depend on specific callback functions. The first step is to create a class that implements an interface named Lifecycle Observer. I'll create a new Kotlin class, that I'll name MyLifecycleObserver. I'll set the kind to Class, and I'll create it. Now I'll indicate that I'm implementing that interface with a colon and the interface name LifecycleObserver. This interface doesn't have any required functions. Instead it has an annotation called OnLifeCycleEvent. For each event that you want to handle, add the annotation, and then in a pair of parentheses, pass the constant indicating which lifecycle event you want to handle. The constant looks like this:…

Contents