I have a code like this:
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
}
Since the value of StateFlow persists even after being collected, after the screen rotates the first lifecycleScope.launchWhenCreated
gets called, collects the flowUser from the flow again, assigns it to the lateinit user
variable, and doThingWithUser
gets called later and everything works fine.
But after two or more rotations, this stops being the case, for some reason user
doesn't get initialized, doThingWithUser
gets called and the app crashes with kotlin.UninitializedPropertyAccessException.
What am I doing wrong? Does the value from StateFlow vanishes after two collections/screen rotations? Something happens with the actual flow inside the ViewModel? Something happens with the onCreate
and onCreateView
methods? Or does launchWhenStarted
and launchWhenCreated
behave differently after two rotations?
Thanks.