Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 104 ยท App Architecture

ViewModel

Learn what an Android ViewModel survives and what it does not, how viewModelScope works, how to create ViewModels with factories and use SavedStateHandle correctly.

When you rotate the phone, the activity is destroyed and created again, and everything it stored in its own fields is gone. Reloading from the network on every rotation would waste data and flicker the screen. The ViewModel is Android's answer: a class whose instance outlives configuration changes and holds the state a screen needs, along with the logic that produces it.

In the architecture from Architecture Layers, the ViewModel is the state holder of the UI layer. It exposes state, receives events and talks to repositories or use cases. This lesson explains how long it lives, how coroutines are tied to it, how to create it with constructor parameters, and when to use SavedStateHandle. It builds on Configuration Changes and Saved State. ViewModel classes need the Android and AndroidX libraries, so those snippets are read-only; the TryIt blocks are stand-ins that reproduce the lifetime rules in plain Kotlin.

A first ViewModel

Kotlin
// read-only example: needs androidx.lifecycle
class CounterViewModel : ViewModel() {
    private val _count = MutableStateFlow(0)
    val count: StateFlow<Int> = _count.asStateFlow()

    fun increment() {
        _count.value += 1
    }
}

@Composable
fun CounterScreen(viewModel: CounterViewModel = viewModel()) {
    val count by viewModel.count.collectAsStateWithLifecycle()
    Button(onClick = viewModel::increment) { Text("Clicked $count times") }
}

The viewModel() function does not simply call a constructor. It asks the nearest ViewModelStoreOwner (the activity, a fragment or a navigation back stack entry) for the instance with a given key. If the store already has one, you get it; otherwise it creates one and stores it. That is why the instance survives a rotation: the activity is replaced, but the store is retained, and the new activity asks the same store.

How the state is exposed as a StateFlow is the subject of StateFlow and collectAsStateWithLifecycle.

How long does it live?

A ViewModel is created the first time something asks for it and is cleared when its owner is gone for good. Here is what it does and does not survive:

Event ViewModel
Rotation, dark mode, language or font-size change Survives
The activity goes to the background and comes back Survives
The user leaves with Back (the activity is finished) Cleared, onCleared is called
A navigation destination is popped (for a per-entry ViewModel) Cleared
The system kills the app's process Lost, and onCleared is not called
flowchart LR
    A["Activity #1<br/>created"] --> B["Rotate:<br/>Activity #1 destroyed"]
    B --> C["Activity #2<br/>created"]
    VM["ViewModel<br/>(same instance)"]
    A -.-> VM
    C -.-> VM
    B --> D["User presses Back:<br/>onCleared"]
    VM -.-> D

The activity instance changes on rotation; the ViewModel instance does not.

The last row of the table is important: a ViewModel is memory, and memory can vanish. Anything the user would be upset to lose (a half-written message, the id of the selected item) must also survive process death, which is what SavedStateHandle is for, covered below.

The lifetime, simulated

The stand-in below models a store that belongs to the host (the "process") and activities that come and go. Each simulated activity asks the store for the ViewModel. It also saves the handle to a bundle, as the framework does. Watch which values survive which event.

Kotlin ViewModel lifetime across recreation and process death (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

On the rotation, the ViewModel is the same object (ViewModel#1) and even the plain draft field survives. After the process death the ViewModel is a new object: draft is lost, but cursor is restored, because it lived in the SavedStateHandle. The real framework has the same split, with the handle saved in the activity's saved-state Bundle for you.

viewModelScope

Coroutines started by a ViewModel must stop when it is cleared; otherwise they keep working for a screen nobody sees. Every ViewModel has a built-in scope for this, viewModelScope:

Kotlin
// read-only example
class ArticlesViewModel(private val repository: ArticleRepository) : ViewModel() {
    private val _state = MutableStateFlow<ArticlesState>(ArticlesState.Loading)
    val state: StateFlow<ArticlesState> = _state.asStateFlow()

    init {
        viewModelScope.launch {
            _state.value = try {
                ArticlesState.Content(repository.articles())
            } catch (e: IOException) {
                ArticlesState.Error("No connection")
            }
        }
    }
}

The scope uses a SupervisorJob (a failing child does not cancel its siblings) and runs on Dispatchers.Main.immediate, so you can update state directly and call suspend functions that switch threads themselves. When the ViewModel is cleared, the scope is cancelled, and all its running coroutines stop with CancellationException. Coroutines on Android goes deeper into dispatchers and main-safety.

Creating a ViewModel with parameters

viewModel() can only call a no-argument constructor on its own. For a ViewModel that needs a repository, you provide a factory. The modern way is the viewModelFactory DSL with initializer:

Kotlin
// read-only example: a factory without a DI library
class ArticlesViewModel(private val repository: ArticleRepository) : ViewModel() {
    // ...

    companion object {
        val Factory = viewModelFactory {
            initializer {
                val app = this[APPLICATION_KEY] as MyApp
                ArticlesViewModel(app.container.articleRepository)
            }
        }
    }
}

@Composable
fun ArticlesRoute(viewModel: ArticlesViewModel = viewModel(factory = ArticlesViewModel.Factory)) {
    // ...
}

The initializer receives CreationExtras, which contain the Application, the SavedStateHandle (key SAVED_STATE_HANDLE_KEY, or the helper createSavedStateHandle()) and any arguments. A dependency injection library such as Hilt generates all this, as you will see in Hilt. The ViewModel itself should never create its dependencies; it receives them in its constructor so that tests can pass fakes.

SavedStateHandle

A SavedStateHandle is a key-value map that is saved with the activity's state and restored after process death. Ask for it as a constructor parameter (Hilt and the factory support it) and use it for small, important pieces of state:

Kotlin
// read-only example
class SearchViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
    val query: StateFlow<String> = savedStateHandle.getStateFlow("query", "")

    fun onQueryChange(newQuery: String) {
        savedStateHandle["query"] = newQuery
    }
}

Rules of thumb:

  • Store small values (ids, queries, selected tabs, scroll positions as numbers). The same size limits apply as for any saved state: a few hundred KB at most, and in practice far less.
  • Store values the Bundle accepts: primitives, strings, Parcelable and Serializable objects.
  • Do not put lists of loaded data or images in it. Store the id and reload the data from the repository.
  • With Navigation Compose, savedStateHandle.toRoute<Product>() reads the route arguments of the destination, which is how a ViewModel learns which product to load (Passing Arguments and Results).

What a ViewModel must never hold

A ViewModel can outlive the activity. If it keeps a reference to something tied to that activity, the old activity cannot be garbage collected: a memory leak.

  • Do not store Context, Activity, Fragment, View or NavController in a ViewModel. If you need a context for something like resources, convert in the UI layer, or use AndroidViewModel, which gives you the Application (this one is safe because it lives as long as the process).
  • Do not keep references to composables or lambdas that capture them.
  • Do not expose mutable state (MutableStateFlow) publicly. Expose read-only types and give the UI functions to call.
  • Do not show UI from the ViewModel, for example by calling Toast. Expose state or one-off events that the UI renders (UI State, Events and MVI-style Modelling).

A ViewModel and its scope, simulated

The second stand-in shows the effect of viewModelScope with real coroutines. The base class launches work on a scope that is cancelled by clear. The coroutine context is passed in, the way a test would pass a test dispatcher, and the constructor shows the factory idea: the ViewModel receives its dependency instead of creating it.

Kotlin viewModelScope is cancelled when the ViewModel is cleared (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real viewModelScope does exactly this, with the main dispatcher in place of runBlocking's context. The finally block runs on cancellation, so cleanup code inside your coroutines still executes.

Common mistakes

  • Holding a Context or Activity in the ViewModel (leak).
  • Expecting the ViewModel to survive process death. Save small, essential state in SavedStateHandle and reload the rest.
  • Creating ViewModels with MyViewModel() yourself. They then are not tied to the owner and die with the screen. Always get them through viewModel(), hiltViewModel() or a factory.
  • Starting work in the ViewModel with GlobalScope. Use viewModelScope.
  • Doing the first load in a composable's LaunchedEffect when it belongs in the ViewModel's init or a stateIn pipeline, so rotation reloads data again.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event does a ViewModel NOT survive?

    A ViewModel lives in memory. Configuration changes keep the store, but when the whole process is killed, every object is gone, so important state needs SavedStateHandle.
  2. 2. What happens to viewModelScope when the ViewModel is cleared?

    The scope is cancelled with the ViewModel, so work for a screen the user has left does not continue.
  3. 3. How do you give a ViewModel a repository parameter without a DI library?

    A factory creates the ViewModel with its dependencies, and the store keeps the instance so it survives configuration changes.
  4. 4. Which value is a good candidate for SavedStateHandle?

    Keep it small: ids, queries and flags. Reload large data from the repository using those ids.

Summary

  • A ViewModel is the UI layer's state holder; it survives configuration changes because the store that holds it is retained.
  • It is cleared (with onCleared) when its owner is finished for good, and it is lost silently on process death.
  • SavedStateHandle keeps small, essential values across process death; reload big data from the repository.
  • viewModelScope is cancelled when the ViewModel is cleared, so launch work there, not in GlobalScope.
  • Create ViewModels through viewModel() and a factory (or Hilt) so dependencies come in through the constructor.
  • Never store Context, Activity, View or NavController in a ViewModel, and do not expose mutable state.
  • The ViewModel code is read-only; the TryIts model its lifetime and scope in plain Kotlin.

Next: UI State, Events and MVI-style Modelling