Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 启动后台任务时附加观察者的正确顺序_Kotlin_Android Livedata_Observers - Fatal编程技术网

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

Kotlin 启动后台任务时附加观察者的正确顺序,kotlin,android-livedata,observers,Kotlin,Android Livedata,Observers,在片段或活动中,是否有建议的顺序来设置观察者与启动数据生成器 例如,假设没有其他人正在获取数据或观察,则: override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // OPTION A: this seems bullet-proof. Setup the observer first,

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

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

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
上没有争用条件,因为它在主线程上传递所有数据