简体   繁体   中英

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 ?

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM