Android ViewModels: Saving State across Process Death

A quick recipe on how to save ViewModel state across android process death.

A misconception among some android developers is that the purpose of using ViewModels is state persistence — it’s actually partly true — they do help in saving state across configuration change (e.g. device rotation) but not process death. So if Android kills your app (let’s say because of low memory), then your app state is lost.

So depending on whether you want to persist your state across process death or not — you can either use in your Fragments/Activities or the new in your ViewModels.

Ok so why and why save/handle states in ViewModels?

Well if you handle your state (for process death) in Activities or Fragments — that’ll add extra verbosity and will cause tight coupling between state-handling & activity/fragment code. Handling your state via ViewModels solves this issue.

Using SavedStateHandle

Add lifecycle-viewmodel-savedstate dependency

Add SavedStateHandle property in your ViewModel

Initialize your ViewModel using SavedStateViewModelFactory

Saving and restoring state

The has methods for setting/getting values.

You can save/restore primitives, bundles and parcelables.

Saving is as easy as:

And restoring:

Restore state as a LiveData

If you want to restore your data as LiveData, theres a getter for that as well.

And that’s it! Make sure to handle all your states!

Happy coding!

Web | Android | Senior Software Engineer @QuixelTools

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store