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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.