37.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.java class file and add code to the onActivityCreated() method to add the observer:
.
.
import com.ebookfrenzy.lifecycledemo.DemoObserver;
.
.
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
getLifecycle().addObserver(new DemoObserver());
}
With the observer class created and added to the lifecycle owner’s Lifecycle object, the app is ready to be tested.