Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • 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?

like image 934
fernandospr Avatar asked Jul 17 '19 17:07

fernandospr


People also ask

How do you observe live data in activity?

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.

Can ViewModel observe LiveData?

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.

Why is Onchanged being called when I navigate back to a fragment?

This is expected because you are resubscribing to a LiveData, and LiveData replays its last emitted value when you subscribe to it.


1 Answers

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.

like image 51
Rodrigo Queiroz Avatar answered Sep 19 '22 18:09

Rodrigo Queiroz