How a ViewModel survives

Lifecycle and app components Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

A ViewModel keeps private val activity: Activity. After a few rotations, memory grows. What's the fix?

Options
Hint 1 of 1

Which lives longer, the ViewModel or the Activity?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Remove the reference; pass data in and expose state out, using the application context if needed

Correct. The ViewModel outlives each Activity instance and leaks it.

Why not the others?
  • B Make the reference a WeakReference and keep using it. It avoids the leak but the design is still wrong; you'd call into a dead Activity.
  • C Clear it in onDestroy. The ViewModel doesn't get onDestroy; and it would still hold the new one.
  • D Use lifecycleScope in the ViewModel. ViewModels don't have a lifecycleScope; they use viewModelScope.

30-second answer

Each Activity, Fragment and navigation entry is a ViewModelStoreOwner with a ViewModelStore, a map of ViewModels. On a configuration change, ComponentActivity keeps that store across the recreation and hands it to the new instance, so by viewModels() finds the existing ViewModel. When the owner finishes for good, the store is cleared and each ViewModel's onCleared runs.

Practise saying it · 35 s. No recording, just a timer

Explain how a ViewModel survives rotation.

Say your answer out loud, then check which of these points you covered:

  • ViewModelStore per owner
  • Kept across configuration changes
  • Cleared when the owner finishes
  • Never hold Activity or View references

Deep dive

The ViewModelProvider looks up a key (the class name by default) in the store before creating a new one.

A Fragment's ViewModels live in a store kept by its FragmentManager; activityViewModels() uses the Activity's store to share between Fragments.

Never hold an Activity, View or Context of a screen in a ViewModel: it outlives them and leaks them.

Use CreationExtras or Hilt to pass dependencies; don't write factories by hand for every class.

Common mistakes

  • Holding a Context or View in a ViewModel.
  • Creating ViewModels with their constructor directly, bypassing the store.
  • Assuming it survives process death.

Senior take & follow-ups

Explain ViewModelStore and onCleared. Mention the leak rule and process death limit.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do two Fragments share state?

    Show hint

    activityViewModels() or a navigation-graph-scoped ViewModel.

  2. What context is safe in a ViewModel?

    Show hint

    The application context, usually via AndroidViewModel or injection.

Suggest a fix if something here is wrong or out of date.