As of 2019, I'm trying to follow a best practice on where to start observing LiveData
in Fragments and if I should pass this
or viewLifecycleOwner
as a parameter to the observe()
method.
According to this Google official documentation, I should observe in onActivityCreated()
passing this
(the fragment) as parameter.
According to this Google sample, I should observe in onViewCreated()
passing viewLifecycleOwner
as parameter.
According to this I/O video, I shouldn't use this
but instead viewLifecycleOwner
, but doesn't specify where should I start observing.
According to this pitfalls post, I should observe in onActivityCreated()
and use viewLifecycleOwner
.
So, where should I start observing? And should I either use this
or viewLifecycleOwner
?
Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.
ViewModel allows the app's data to survive configuration changes. In this codelab, you'll learn how to integrate LiveData with the data in the ViewModel . The LiveData class is also part of the Android Architecture Components and is a data holder class that can be observed.
This is expected because you are resubscribing to a LiveData, and LiveData replays its last emitted value when you subscribe to it.
If observing from an Activity you can observe on onCreate()
and use this
for the LifecycleOwner as stated here:
If you have a lifecycle-aware component that is hooked up to the lifecycle of your activity it will receive the ON_CREATE event. The method annotated with @OnLifecycleEvent will be called so your lifecycle-aware component can perform any setup code it needs for the created state.
Now if you are observing within a Fragment you can observe on onViewCreated()
or onActivityCreated()
and you should use getViewLifecycleOwner()
and here is why:
Get a LifecycleOwner that represents the Fragment's View lifecycle. In most cases, this mirrors the lifecycle of the Fragment itself, but in cases of detached Fragments, the lifecycle of the Fragment can be considerably longer than the lifecycle of the View itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With