on memory Configuration Changes User can swipe away your app App crashes in background App updated in background System need resources Unexpected app dismissal How app lose state
transient data for State Configuration Changes Recover from unexpected state Save data to storage System need resources Unexpected app dismissal How to preserve state
NAME_KEY = "name"; private SavedStateHandle mState; public SavedStateViewModel(SavedStateHandle savedStateHandle) { mState = savedStateHandle; } // Expose an immutable LiveData LiveData<String> getName() { // getLiveData obtains observable object for the key, wrapped in a LiveData return mState.getLiveData(NAME_KEY); } void saveNewName(String newName) { // Sets a new value for the object associated to the key mState.set(NAME_KEY, newName); } }
by savedStateHandle.saveable( stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue("")) } private set fun update(newMessage: TextFieldValue) { message = newMessage } fun send() { /* Send current message to the data layer */ } } SavedStateHandle
Yes Yes Yes Survives system initiated death No Yes Yes Survives user complete activity dismiss/finish No No Yes Data limitation Space is limited ~ 50KB, primitive data Available disk space / cost Read write time Quick Slow (serialization) Slow (Disk / Network IO) ViewModel Save API Persistent Storage How to preserve state