【问题标题】:Correct order of attaching Observer when Starting Background Task启动后台任务时附加观察者的正确顺序
【发布时间】:2021-07-02 16:17:20
【问题描述】:

在片段或活动中,是否有推荐的顺序来设置观察者和启动数据生产者?

例如,假设没有其他人在获取数据或观察,那么:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
 ): View? {

    // OPTION A: this seems bullet-proof. Setup the observer first, 
    //  then trigger the generation of the data...
    // ----------------------------------------------------------
    // 1) setup observer
    mainViewModel.myResponse.observe(viewLifecycleOwner, { response -> {...} })

    // 2) initiate data fetching
    mainViewModel.generateFetchInBackground()

    // OPTION B: this is what I sometimes see done. This seems like
    //   a race condition since the triggering of generation happens
    //   first, then the observer is established...
    // ----------------------------------------------------------
    // 1) initiate data fetching
    mainViewModel.generateFetchInBackground()        
    
    // 2) setup observer
    mainViewModel.myResponse.observe(viewLifecycleOwner, { response -> {...} })

}

【问题讨论】:

    标签: kotlin android-livedata observers


    【解决方案1】:

    何时开始提供数据或观察数据并不重要。 LiveData 保证所有值都将在您的观察者become active 时传递给他们。

    当您更新存储在 LiveData 对象中的值时,只要附加的 LifecycleOwner 处于活动状态,它就会触发所有已注册的观察者。 LiveData 允许 UI 控制器观察者订阅更新。当 LiveData 对象持有的数据发生变化时,UI 会自动更新作为响应。

    这就是LiveData 帮助您解耦生产者和观察者的原因。 LiveData 上没有竞态条件,因为它在主线程上传递所有数据。

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多