DEV Community

Cover image for Don't think Viewmodel will replace SaveInstanceState
Randy Arba
Randy Arba

Posted on • Edited on

Don't think Viewmodel will replace SaveInstanceState

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 onSaveInstanceStateand 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.

Top comments (3)

Collapse
 
funkymuse profile image
FunkyMuse

Viewmodel has save instance state already.

developer.android.com/reference/an...

Collapse
 
leviaran profile image
Randy Arba

Yes true, but this save/load state only trigger when activty/fragmenst still alive.

Collapse
 
funkymuse profile image
FunkyMuse • Edited

It's bound to the fragment so the view model gets new instance if not instantiated already when fragment is recreated