【发布时间】:2022-01-23 06:53:51
【问题描述】:
我有这样的代码:
private val appViewModel: AppViewModel by activityViewModels()
private lateinit var user: User
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This sets the variable user to the value collected from a StateFlow from appViewmodel
lifecycleScope.launchWhenCreated {
appViewModel.user.collect { flowUser -> user = flowUser }
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// This method utilizes the lateinit user variable
lifecycleScope.launchWhenStarted {
doThingWithUser()
}
return binding?.root
}
由于 StateFlow 的值在被收集后仍然存在,因此在屏幕旋转后第一个 lifecycleScope.launchWhenCreated 被调用,从 flowflowUser /em> 再次将其分配给lateinit user 变量,稍后调用doThingWithUser 一切正常。
但是在两次或多次旋转之后,情况就不再是这种情况了,由于某种原因,user 没有被初始化,doThingWithUser 被调用并且应用程序因 kotlin.UninitializedPropertyAccessException 而崩溃。
我做错了什么? StateFlow 中的值是否在两次收集/屏幕旋转后消失? ViewModel 中的实际 flow 发生了什么? onCreate 和 onCreateView 方法发生了什么?还是launchWhenStarted 和launchWhenCreated 在两次旋转后表现不同?
谢谢。
【问题讨论】:
标签: android kotlin-coroutines android-lifecycle activity-lifecycle fragment-lifecycle