In Activity or Fragment, during onCreate, we will know if it is a restored State or not e.g.
override fun onCreate(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
// This is a newly created View
} else {
// This is a restored View
}
}
In ViewModel, we have SavedStateHandler too.
class MyViewModel(val savedStateHandle: SavedStateHandle) : ViewModel() {
init {
// How can I know if this is a restored state or a newly created Viewmodel?
}
}
But is it possible to know if it is a restored state or not in ViewModel?
If you use the SavedStateHandle to save something that you need in your ViewModel, just check if it exists, if it does then the ViewModel is restoring from the saved state.
If you don't save anything, but just want to follow the same logic as what you showed above, then you can do something like this: