Sources of Owners
observe() on a LiveData takes a LifecycleOwner. Technically, you could implement the LifecycleOwner interface on just about anything. In practice, there are three commonly-used LifecycleOwner implementations:
-
FragmentActivityand things that inherit from it, likeAppCompatActivity Fragment- The “view
LifecycleOwner” of aFragment
The first two are fairly straightforward. They let the LiveData know about the lifecycle of the activity and the fragment, respectively.
However, as we noted earlier fragments are weird, with their pair of lifecycles:
- The lifecycle of the fragment itself
- The lifecycle of a particular UI managed by that fragment
The general rule of thumb is:
- If you are observing a
LiveDatasolely for populating a UI, such as we are doing here inColorListFragment, usegetViewLifecycleOwner()as theLifecycleOwnerand start observing inonViewCreated()(or possibly inonCreateView()) - If you are observing a
LiveDataand need to observe for the entire lifetime of the fragment, regardless of its UI, use theFragmentitself as theLifecycleOwnerand start observing inonCreate()… but do not attempt to update any views in response to thatLiveData, as they may not exist at the time you receive an updated value
The first pattern is by far the most common one.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.