tezvyn:

ViewModel: Surviving Android Configuration Changes

AI-drafted, machine-checkedSource: developer.android.comintermediate
ViewModel: Surviving Android Configuration Changes

A ViewModel acts like a durable backpack for your UI's data, surviving the destruction and recreation of an Activity during a screen rotation. It holds UI state, like user input or fetched data, preventing data loss.

WHY IT EXISTS: Android destroys and recreates UI controllers like Activities on configuration changes, such as screen rotation or language switching. This default behavior wipes out any state held in memory, like user input or fetched data, creating a jarring experience and forcing unnecessary work like new network calls.

THE MENTAL MODEL: A ViewModel is a data container designed to outlive the UI controller it's associated with. It's like a durable backpack for your UI's data. When an Activity is destroyed during rotation, it's temporarily detached from its ViewModel. When the new Activity instance is created, it reconnects to the exact same ViewModel instance, finding its data intact.

HOW IT WORKS: When you request a ViewModel for a specific scope (like an Activity), the Android framework acts as a custodian. It checks if a ViewModel instance for that scope already exists. If so, it returns the existing one. If not, it creates a new one and retains it. This retained object is only cleared when the scope is permanently destroyed, not during temporary configuration changes.

WHEN TO USE IT: Use a ViewModel to store and manage all data the UI displays. This is the correct place to hold user input from forms, lists of data fetched from a server, and the general state of your screen. It acts as the single source of truth for the UI, exposing its data through observable streams like StateFlow or LiveData.

WHEN NOT TO USE IT: Never store references to Views, Composables, or a Context in a ViewModel. This is a classic memory leak. The ViewModel outlives the UI, so holding a reference to a destroyed Activity prevents it from being garbage collected. Also, a ViewModel by itself does not survive process death; it is not a substitute for persistent storage or the SavedStateHandle.

ONE CANONICAL EXAMPLE: A user types a search query into an EditText. They rotate their phone. Without a ViewModel, the Activity is recreated and the EditText is now empty. With a ViewModel, the query is stored in a StateFlow. The new Activity instance connects to the existing ViewModel, observes the StateFlow, and immediately restores the query to the EditText. The user's input is seamlessly preserved across the configuration change.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.