[英]After two or more screen rotations, lifecycleScope.launchWhenCreated stops working as expected
我有這樣的代碼:
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
Scope.launchWhenCreated 被調用,再次從流中收集flowUser ,將其分配給 lateinit user
變量,稍后再調用doThingWithUser
,一切正常。
但是經過兩次或多次旋轉后,情況就不再如此了,由於某種原因, user
沒有被初始化, doThingWithUser
被調用並且應用程序因kotlin.UninitializedPropertyAccessException而崩潰。
我究竟做錯了什么? 兩次收集/屏幕旋轉后, StateFlow的值是否消失? ViewModel內部的實際流程發生了什么? onCreate
和onCreateView
方法發生了什么? 還是launchWhenStarted
和launchWhenCreated
在兩次旋轉后表現不同?
謝謝。
我發現了問題所在。 顯然,導航組件與片段生命周期的順序相混淆,如此處所示。
因此,當屏幕旋轉時,由於 backstack 順序,Navigation 正在創建另一個 Fragment,該 Fragment 也與當前 Fragment 之前的ViewModel的StateFlow交互。 因此,另一個片段onCreate
方法正在向流程發送其他內容,因此弄亂了我當前的片段集合。
解決方案是使流集合獨立於片段生命周期,或者更改任一故障片段中的集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.