我有一个保存一些实时数据的视图模型(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,甚至从视图模型observe方法调用协程来解决这个问题,但这段代码使用的是保存状态的新视图模型,所以我真的不想使用这些选项中的任何一个,我只是想知道是否有办法让它按我想要的顺序调用?
此外,我猜测这要么与视图模型初始化数据所需的时间有关,要么是因为我对视图模型使用viewLifecycleOwner,对作为调度器的协同程序使用lifecycleScope.launch。Main.immeediate,但如果有人对为什么会发生这种情况有明确的解释,我将不胜感激。
我试着移动订单,调用onCreateView和onCreate都没有用
LMAO在我发布这篇文章时,我将我的协同程序更改为使用Dispatchers.Main,它在lol 中工作