ViewModel
Versus…
The objective of ViewModel
, in particular, is to be able to survive past configuration changes.
Of course, we have been dealing with configuration changes for years, before the Architecture Components were a glimmer in any Google engineer’s eye.
So, when would we use a ViewModel
, and when would we use other techniques?
…Saved Instance State
Saved instance state — what you put into the Bundle
supplied to onSaveInstanceState()
— survives process termination. A ViewModel
does not. So while both can help deal with configuration changes, only saved instance state can help with the process termination scenario:
- User is in your app, in an activity
- User navigates to something else (e.g., presses HOME, switches to another task via the overview screen)
- A few minutes later, Android terminates your process to free up system RAM
- A few minutes after that — but within 30 minutes of the user navigating away — the user returns to your task
- Android recreates the activity atop your task’s back stack as part of forking a fresh process for you, and Android hands you your saved instance state
Bundle
back
However, the saved instance state Bundle
has size limits (should be well under 1MB) and type limits (only objects that can go into a Parcel
).
As a result:
- Use the
ViewModel
for holding onto data in your process necessary to be able to rapidly repopulate the UI after a configuration change - Use the saved instance state
Bundle
to hold identifiers and other data that will help you rebuild the UI after process termination, even if you wind up having to re-read from disk or the network as part of that work
…Retained Objects
In the end, the ViewModelProviders
system supplied by the Architecture Components is a wrapper around retained fragments. As a result, there is nothing that you can do with a ViewModel
that you could not do using retained objects, whether those are retained fragments or using onRetainCustomNonConfigurationInstance()
.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.