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! Aren't ViewModels
supposed to handle these situations?
I can handle this problem by saving my activity's state in onSaveInstanceState
but then what's the point of using a ViewModel
?
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:
Bitmap
of a photo)LiveData
, RxJava Observable
, etc.)Socket
in a Bundle
)