Sobes.tech
Junior — Middle

Which mechanism is better to use for saving UI state: ViewModel or SaveInstanceState, and how do they differ?

sobes.tech AI

Answer from AI

ViewModel and SaveInstanceState are used to preserve UI state, but they operate differently and are intended for different tasks.

  • ViewModel stores data in memory during configuration changes (e.g., screen rotation). It lives as long as the Activity or Fragment, and is not destroyed during UI recreation. ViewModel is suitable for storing large amounts of data and business logic.

  • SaveInstanceState is a mechanism for saving small amounts of data in a Bundle, which is preserved when the Activity is destroyed by the system (e.g., due to low memory). Data from SaveInstanceState is restored when the Activity is recreated.

Which is better to use?

  • For preserving UI state that should survive a screen rotation, it is better to use ViewModel.
  • For saving critical data that must be restored after the app is completely destroyed by the system, SaveInstanceState is used.

They are often combined: ViewModel for main logic and data, SaveInstanceState for small primitive data that needs quick restoration.