Have you ever thought about what happens after we die? No one knows. But there is something we know: When an app dies, we lose state.
Unfortunately mobile devices don’t have unlimited battery or unlimited memory. That’s why when system needs more memory, it kills processes to make some room. So we should make sure that our apps are not effected by this process death. Although it is very important in terms of user experience, the solution is quite easy.
Let’s see an example; We have an application where we fetch user details when Get User button is clicked. This is the initial state of the application.
When we click on Get User button, we fetch user details from an API and update the UI.
We have a simple ViewModel that keeps the UI state;
BUT if system kills the app when the application is on the background, user will see the initial/empty state when the app is reopened.
To simulate process death in Android Studio;
Go to Logcat -> Terminate Application
Or you can enable “Don’t keep activities” option in Developer Settings of the device.
So how do we prevent state loss in this situation? How do we save the state and how do we handle it? We use SavedStateHandle :
As soon as we update the UI state, we save it to the SavedStateHandle and when app is relaunched, we check if we have saved state or not. It is that simple!
There are some key points that we need to consider while applying this solution;
You can check the sample application in the repo below: