我有一个包含一些实时数据的视图模型(hasExpanded)和一个在onViewCreated中调用的协程,但是协程总是首先执行,例如:
@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或sharedPreference或者甚至从视图模型观察方法调用协程来解决这个问题,但是这段代码使用的是带有保存状态的新视图模型,所以我并不真的想求助于这些选项中的任何一个,我只是想知道是否有一种方法可以让它按我想要的顺序调用?
此外,我猜测这可能与视图模型初始化数据所需的时间有关,也可能是因为我对视图模型使用viewLifecycleOwner,对协程使用lifecycleScope.launch,协程是dispatchers.Main.immediate,但如果有人对此有明确的解释,我将不胜感激。
我已经尝试移动订单,调用onCreateView和onCreate都无济于事
发布于 2020-10-22 04:53:29
当我发布这篇文章时,我将我的协程改为使用Dispatchers.Main,并且它工作了。
https://stackoverflow.com/questions/64471583
复制相似问题