【问题标题】:Are there any reasons to ever scope LiveData to a fragment's lifecycle, rather than to the fragment's view's lifecycle?是否有任何理由将 LiveData 范围限定为片段的生命周期,而不是片段视图的生命周期?
【发布时间】:2018-11-02 21:44:55
【问题描述】:

如果我们通过将this 传递给observe 方法将LiveData 范围限定为fragment 的生命周期,那么如果fragment 仅与活动分离,则它不会立即更新,但不会立即更新删除,因为只有 view 被销毁,而不是 fragment 实例本身。

相反,我们可以将LiveData 限定为片段的view 的生命周期,方法是在onActivityCreated 中调用observe 并传递getViewLifecycleOwner() 而不是this

是否有任何理由不将LiveData 限定为fragmentview

【问题讨论】:

    标签: android android-fragments android-architecture-components android-livedata


    【解决方案1】:

    如果您的片段没有 UI,那么您需要使用片段的生命周期来确定它的范围。 许多人/库使用并且仍然使用无头(UI-Less)工作片段来具有生命周期意识,以安全地将异步检索的数据(网络调用)传递给 UI。 (类似于 Loaders 所做的)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      相关资源
      最近更新 更多