Android 协同程序视图模型执行
我有一个视图模型,它保存一些实时数据(hasExpanded),还有一个在onViewCreated中调用的协程,但协程总是首先执行,例如:Android 协同程序视图模型执行,android,kotlin-coroutines,android-viewmodel,Android,Kotlin Coroutines,Android Viewmodel,我有一个视图模型,它保存一些实时数据(hasExpanded),还有一个在onViewCreated中调用的协程,但协程总是首先执行,例如: @ExperimentalCoroutinesApi override fun onViewCreated(view: View, savedInstanceState: Bundle?) { setActionBar() super.onViewCreated(view, savedInstanceState) observeHa
@ExperimentalCoroutinesApi
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setActionBar()
super.onViewCreated(view, savedInstanceState)
observeHasExpandedState()
viewLifecycleOwner.lifecycleScope.launch {
Log.d("DETAIL", "launch")
if (!hasExpanded){
Log.d("DETAIL", "!hasExpanded")
Log.d("DETAIL", "setImageView started")
setImageView(imageUrl) // waits for a callback to complete
Log.d("DETAIL", "setImageView finished")
Log.d("DETAIL", "handleEnterAnimation started")
handleEnterAnimation() // waits for animation to complete
Log.d("DETAIL", "handleEnterAnimation finished")
viewModel.setRevealAnimationExpandedState(true)
}
observeSomeOtherData()
}
}
private fun observeHasExpandedState() {
viewModel.revealAnimationExpanded.observe(
viewLifecycleOwner,
Observer { hasExpanded ->
Log.d("DETAIL", "hasExpanded changed - $hasExpanded")
this.hasExpanded = hasExpanded
}
)
}
从这里我希望D/DETAIL:hasExpanded changed-false首先被打印出来,但是上面的代码将打印类似这样的内容
D/DETAIL: launch
D/DETAIL: !hasExpanded
D/DETAIL: setImageView started
D/DETAIL: hasExpanded changed - false # (I want to have this called first)
D/DETAIL: setImageView started
D/DETAIL: setImageView finished
D/DETAIL: handleEnterAnimation started
D/DETAIL: handleEnterAnimation finished
D/DETAIL: hasExpanded changed - true
D/DETAIL: observeSomeOtherData
我可以通过使用savedInstanceState或SharedReference,甚至从view model observe方法调用协程来解决这个问题,但是这段代码使用的是新的视图模型和saved state,所以我真的不想求助于这些选项,我只是想知道是否有办法按照我想要的顺序调用它
此外,我猜这可能与视图模型初始化数据所需的时间有关,也可能是因为我对视图模型使用viewLifecycleOwner,而对协同程序使用lifecycleScope.launch,即dispatchers.Main.immediate,但如果有人对为什么会发生这种情况有明确的解释,我将不胜感激
我试着移动订单,调用onCreateView和onCreate都没有用LMAO当我发布此消息时,我将我的协同程序更改为使用Dispatchers.Main,它成功了lol