Interview frequency: …
Short answer
It stores and restores the ViewModel's essential lightweight state (such as identifiers and search text) automatically when the system ends the app's process in the background, and works as a key-value map integrated with StateFlow.
Explanation
While the ViewModel protects from screen rotation, it does not protect from the system killing the entire process to save memory. Hilt automatically injects SavedStateHandle into a ViewModel, and it allows reading navigation arguments and saving lightweight state through getStateFlow(), so they are restored automatically and smoothly once the screen restarts.
Code example
class DetailViewModel(
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
// Read a parameter passed through Navigation Component:
val userId: String = checkNotNull(savedStateHandle["userId"])
// Convert the value to a reactive stream:
val query: StateFlow<String> = savedStateHandle.getStateFlow("query", "")
fun updateQuery(newQuery: String) {
savedStateHandle["query"] = newQuery
}
}Common mistakes
- Storing complex objects or huge lists in SavedStateHandle, which exceeds the 1MB limit allowed for the Binder system.