fernandospr
fernandospr

Reputation: 3051

LiveData observing in Fragment

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.

So, where should I start observing? And should I either use this or viewLifecycleOwner?

Upvotes: 44

Views: 16661

Answers (3)

Rodrigo Queiroz
Rodrigo Queiroz

Reputation: 2844

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.

Upvotes: 25

Arka Prava Basu
Arka Prava Basu

Reputation: 2560

As in the I/O talk Yigit says, the Fragment and its view has different lifecycles. You would need to identify if your LiveData is related to the fragment or its view and pass the one desired. The compiler will accept both since both are implementations of LifecycleOwner

Upvotes: 2

Francesc
Francesc

Reputation: 29260

It doesn't matter whether you do it on onViewCreated or onActivityCreated. Both are called when the fragment is inflated, onViewCreated first, onActivityCreated afterwards. It's really a matter of preference.

The LiveData object takes a LifecycleOwner, and both Fragment and Activity implement the interface, so you just need to pass this.

Upvotes: -1

Related Questions