ViewModel & LiveData
Survive configuration changes with ViewModel. Expose reactive data streams with LiveData and observe them in Activities and Fragments.
The Problem with Activities
Storing data directly in an Activity has two major problems:
- When the user rotates the phone, the Activity is destroyed and recreated — all your data is lost
- If you fetch data from the network in
onCreate, it re-fetches on every rotation — wasteful
ViewModel solves both problems.
What Is ViewModel?
ViewModel is an Android Architecture Component that:
- Survives configuration changes (rotation, theme change)
- Holds UI-related data and business logic
- Is destroyed only when the user permanently leaves the screen
Rule of thumb: if data should survive rotation, put it in a ViewModel.