Enter the ViewModel
So, a configuration change destroys and recreates our activity, by default. As a result, anything that is held onto uniquely by an activity instance — such as our random numbers — gets lost when we switch to the new activity instance, by default.
What would be nice is if we could separate our activity data into two groups:
- Part of our data, such as references to widgets, can be discarded on a configuration change, as we will need to get fresh data in the new activity
- Part of our data, such as our random numbers, could be passed from the old activity instance to the new activity instance, so we can present that data again to the user
The Jetpack solution for this is ViewModel
. We can create a subclass of ViewModel
that holds onto the second category of activity data: the stuff that we want to reuse after the configuration change. Jetpack will take the steps necessary to get that data — indeed, typically the entire ViewModel
object — from the old activity instance to the new one. All that we need to do is make intelligent choices about what goes into the ViewModel
and what does not.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.