In this case, the Fragment is inflated from a <fragment>
tag in the Activity's layout, so the lifecycle of the Fragment and the Activity is always the same so it doesn't make any difference.
However, there are two cases where this fails badly:
- If you
remove()
or replace()
the Fragment, using getActivity()
for your LifecycleOwner
will result in leaking the Fragment since the LiveData holds a strong reference to the Observer (and hence, the Fragment since it is a non-static inner class) until the Activity is destroyed
- If you
detach()
and then attach()
the Fragment (such as with a FragmentPagerAdapter
), then using the Fragment's lifecycle in onCreateView()
will result in multiple Observers since onCreateView()
is called each time the Fragment's view is recreated upon attach and previous Observers are not destroyed since the Fragment's lifecycle has not been destroyed.
The correct LifecycleOwner
to use in onCreateView()
is always getViewLifecycleOwner()
since this lifecycle is destroyed when the Fragment's View is destroyed:
mSeekBarViewModel.seekbarValue.observe(getViewLifecycleOwner(), new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer value) {
if (value != null) {
mSeekBar.setProgress(value);
}
}
});
This prevents leaking the Fragment by using a potentially longer lifespan LifecycleOwner
(like the Activity) and prevents multiple Observers being registered when using patterns like those employed by FragmentPagerAdapter
.