在一个片段或一个活动中,是否有建议的设置观察者与启动数据生产者的顺序?
例如,假设没有其他人在获取数据或观察,那么:
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
保证所有值在它们激活时都会传递给您的观察者。
更新LiveData对象中存储的值时,只要连接的LifecycleOwner处于活动状态,它就会触发所有注册的观察者。LiveData允许UI控制器观察员订阅更新。当LiveData对象所保存的数据发生更改时,UI会自动更新作为响应。
这就是LiveData
帮助您解耦生产者和观察者的原因。并且LiveData
上没有竞争条件,因为它在主线程上传递所有数据。