Let's say that we have a simple fragment with a view based on the UI state held in StateFlow
in the view model.
On onCreate()
we collect state as usually:
override fun onCreate(savedInstanceState: Bundle?) {
lifecycleScope.launchWhenStarted {
viewModel.uiState.collect {
// UI update according to state
}
}
}
Now we navigate to the next fragment - the previous is kept by the fragment manager, but the view is destroyed. On the new fragment, we pop back stack and now is surprising: the previous fragment is recreating the view on the initial state and even if we try to update state flow nothing will happen since it doesn't emit equal data twice one by one.
So, how to restore the view state after return to the fragment?