DEV Community

myougaTheAxo
myougaTheAxo

Posted on

ViewModel SavedStateHandle Guide — Surviving Process Death in Android

What You'll Learn

How to use SavedStateHandle to preserve ViewModel state across process death.

Why SavedStateHandle?

Regular ViewModel variables live in memory only — they're lost on process death. SavedStateHandle saves state via Bundle, surviving process death and restoration.

Basic Usage

class SearchViewModel(
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    val query: StateFlow<String> = savedStateHandle.getStateFlow("query", "")
    val selectedTab: StateFlow<Int> = savedStateHandle.getStateFlow("selectedTab", 0)
    fun updateQuery(newQuery: String) { savedStateHandle["query"] = newQuery }
    fun selectTab(index: Int) { savedStateHandle["selectedTab"] = index }
}
Enter fullscreen mode Exit fullscreen mode

Navigation Arguments

class UserDetailViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
    private val userId: String = checkNotNull(savedStateHandle["userId"])
    init { loadUser(userId) }
}
Enter fullscreen mode Exit fullscreen mode

With Hilt

@HiltViewModel
class TodoViewModel @Inject constructor(
    private val repository: TodoRepository,
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    val filter: StateFlow<String> = savedStateHandle.getStateFlow("filter", "all")
    val todos = filter.flatMapLatest { f ->
        when (f) {
            "active" -> repository.getActiveTodos()
            else -> repository.getAllTodos()
        }
    }.stateIn(viewModelScope, SharingStarted.Lazily, emptyList())
}
Enter fullscreen mode Exit fullscreen mode

Summary

  • SavedStateHandle for process death survival
  • getStateFlow() for reactive state management
  • Navigation arguments via SavedStateHandle
  • Hilt auto-injection support

8 production-ready Android app templates on Gumroad.
Browse templatesGumroad

Top comments (0)