gpt4 book ai didi

android - 在 Fragment 中观察 LiveData

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:26 26 4
gpt4 key购买 nike

截至 2019 年,我正在尝试遵循最佳实践,了解从哪里开始观察 Fragments 中的 LiveData 以及我是否应该传递 thisviewLifecycleOwner 作为 observe() 方法的参数。

  • 根据这个Google official documentation ,我应该在 onActivityCreated() 中观察传递 this( fragment )作为参数。

  • 根据这个Google sample ,我应该在 onViewCreated() 中观察传递 viewLifecycleOwner 作为参数。

  • 根据这个I/O video ,我不应该使用 this 而应该使用 viewLifecycleOwner,但没有指定我应该从哪里开始观察。

  • 根据这个陷阱post ,我应该在 onActivityCreated() 中观察并使用 viewLifecycleOwner

那么,我应该从哪里开始观察呢?我应该使用 this 还是 viewLifecycleOwner

最佳答案

如果从 Activity 观察,您可以观察 onCreate() 并将 this 用于 LifecycleOwner,如 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.

现在,如果您在 Fragment 中观察,您可以在 onViewCreated()onActivityCreated() 上观察,您应该使用 getViewLifecycleOwner()here是为什么:

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.

关于android - 在 Fragment 中观察 LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57081763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com