Randy Arba
Posted on November 9, 2019
Different Capabilities
Maybe some developer will excited about the ViewModel
when it can save the state, and someone will thinking to replace SaveInstanceState
into ViewModel
. After that you implement that you will get some mistake.
ViewModel
will only preserve data onConfigurationChange
and when activity/fragment still processed and not get killed. So when you get state after activity get killed you should implement onSaveInstanceState
and onRestoreInstaceState
without ViewModel
. So would you choose one of them or use both of them. actually Viewmodel
and SavedInstanceState
complete each other, such as overlap in capability but not as a subset or superset of the other. You still need both of that.
ViewModel
and SaveInstancesState
can kept the state onConfigurationChanes
, but only SaveInstanceState
do that although the activity get killed.
So storing state when event activity or fragment is killed by system, you will need onSaveInstanceState
or onRestoreINstanceState
not ViewModel
. or the other alternative you can use StateSaveHandle
.
But ViewModel
have the other capability that SaveInstanceState
dont have. ViewModel
can continue operation process that was already started before confguration change.
I will give some example, lets imagine when your device in portrait screen, and you try to request some API but you have poor connection, before the request complete you try to rotate your device into landscape, and look what happen. If you use SaveInstanceState
your current request will terminate first and then start the request again or restart the process. the other hand if you use ViewModel
, when you trigger configuration change the current process/request wouldnt terminated it will continue.
Conclusion
ViewModel
can keep state when the activity/fragment still alive, and then it can continue current process after configuration change. While SavedInstanceState
can keep sate when activity/fragment alive or get killed, but the other hand when configuration change the current process will terminate and restart the process again.
Posted on November 9, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.