46.3 Adding the Observer
Observers are added to lifecycle owners via calls to the addObserver() method of the owner’s Lifecycle object, a reference to which is obtained via a call to the getLifecycle() method. Edit the MainFragment.kt class file and add code to the onActivityCreated() method to add the observer:
.
.
import com.ebookfrenzy.lifecycledemo.DemoObserver
.
.
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
lifecycle.addObserver(DemoObserver())
}
With the observer class created and added to the lifecycle owner’s Lifecycle object, the app is ready to be tested.