启动后台任务时附加观察者的正确顺序

Correct order of attaching Observer when Starting Background Task

在片段或 activity 中,是否有建议的顺序来设置观察者与启动数据生产者?

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

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 -> {...} })

}

何时开始提供数据或观察数据并不重要。 LiveData 保证所有值都将在 become active.

时传递给您的观察者

When you update the value stored in the LiveData object, it triggers all registered observers as long as the attached LifecycleOwner is in the active state. LiveData allows UI controller observers to subscribe to updates. When the data held by the LiveData object changes, the UI automatically updates in response.

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