Challenge: Observing View LifecycleOwner LiveData

PhotoGalleryFragment calls viewLifecycleOwner.lifecycle.observe(…) in Fragment.onCreateView(…). This is simple and works fine so long as the view you return from onCreateView(…) is not null.

You cannot directly observe the view’s lifecycle in Fragment.onCreate(…), because the view lifecycle is only valid from when Fragment.onCreateView(…) is called until Fragment.onDestroyView(…) is called. However, you can observe the lifecycle of a fragment’s view by calling Fragment.getViewLifecycleOwnerLiveData(), which returns a LiveData<LifecycleOwner>. The fragment’s viewLifecycleOwner is published to the live data once a non-null view is returned from Fragment.onCreateView(…) and is set to null ...

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.