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:

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:

…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.