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 after Fragment.onDestroyView(…) is called.

For this challenge, refactor your code to observe the fragment’s viewLifecycleOwner through the LiveData<LifecycleOwner> returned from Fragment.getViewLifecycleOwnerLiveData(). The newly added observer relationship should be tied to the life of the fragment instance. When a non-null value is published, observe the fragment’s view lifecycle, accessible through viewLifecycleOwner.lifecycle.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.210.78.150