When I try to simulate configuration change in my app by enabling "Don't keep activities" in developer options every time I leave an activity and return, the ViewModel is recreated!
AFAIK, "don't keep activities" destroys activities when you navigate away from them. It does not simulate configuration changes.
On Android 8.1, the setting specifically states: "Destroy every activity as soon as the user leaves it".
Aren't ViewModels supposed to handle these situations?
The ViewModel
system handles configuration changes. It does not handle activities being destroyed or processes being terminated.
To simulate a configuration change, change the configuration. For example, you could rotate the screen or change your locale.
I can handle this problem by saving my activity's state in onSaveInstanceState
Anything that can go into the saved instance state Bundle
should go into the saved instance state Bundle
, as that handles both configuration changes and process termination.
what's the point of using a ViewModel?
ViewModel
is there for things that cannot go into the saved instance state Bundle
, such as:
- Big things (
Bitmap
of a photo)
- Live things (
LiveData
, RxJava Observable
, etc.)
- Wrongly-typed things (you cannot put a
Socket
in a Bundle
)
- Things that are not really part of the "instance state" and should not be needed in case Android terminates the process, but you would like to have them around for a simple configuration change
- And so on