tezvyn:

What is a ViewModel and what lifecycle problem does it solve?

Curated by the Tezvyn teamSource: developer.android.combeginner
What is a ViewModel and what lifecycle problem does it solve?

Tests config-change survival: ViewModel outlives Activity recreation so state survives rotation. Strong answer notes it holds non-serializable data and separates concerns, but does not survive process death.

WHAT THIS TESTS: Whether you understand the difference between an Activity instance lifecycle and the user's conceptual screen session, and whether you know where to place non-UI logic so it survives configuration changes without leaking memory.

A GOOD ANSWER COVERS four things in order. First, define the problem: when the device rotates, the system destroys and recreates the Activity or Fragment by default, so any instance variables or async results held directly in the UI controller are lost. Second, explain ViewModel's scope: it is retained as long as the ViewModelStoreOwner (usually an Activity or Fragment) is alive in the back stack, which means it survives configuration changes but is cleared when the owner is finished for good, such as on back press. Third, describe what belongs inside: UI-related data that is expensive to reload, non-serializable objects like LiveData or Flow subscribers, and business logic that should not live in the Activity. Fourth, draw the boundary with onSaveInstanceState: ViewModel does not survive process death, so transient UI state still needs to be saved via onSaveInstanceState or SavedStateHandle for system-initiated destruction.

COMMON WRONG ANSWERS include saying ViewModel prevents all memory leaks automatically, claiming it replaces onSaveInstanceState entirely, or confusing it with the deprecated retained fragment pattern. Another red flag is stating that ViewModel survives process death without mentioning SavedStateHandle.

LIKELY FOLLOW-UPS include how ViewModel is actually retained under the hood via ViewModelStore and a factory, how to share a ViewModel between fragments using the Activity scope, and when to use SavedStateHandle versus plain ViewModel fields.

ONE CONCRETE EXAMPLE: A user opens a news app and loads a list of fifty articles. Without a ViewModel, rotation triggers a new network request because the Activity is recreated and the list variable is null. With a ViewModel, the articles list lives in the ViewModel, survives rotation, and the new Activity instance simply re-observes the same data without another request.

Source: developer.android.com

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.

What is a ViewModel and what lifecycle problem does it solve? · Tezvyn