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
?
The ViewModel class allows data to survive configuration changes such as screen rotations. Usually, one of the first things we find out when learning Android development is that activities get re-created after configuration changes. When it happens, we lose all initialized variables and the view gets re-rendered.
ViewModel classes are used to store the data even the configuration changes like rotating screen. ViewModel is one of the most critical class of the Android Jetpack Architecture Component that support data for UI components. Its purpose is to hold and manage the UI-related data.
ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. FYI: You can use ViewModel to preserve UI state only during a configuration change, nothing else as explained perfectly in this official doc.
The AndroidViewModel extends ViewModel , so it has all the same functionality. The only added functionality for AndroidViewModel is that it is context aware: when initializing AndroidViewModel you have to pass the Application context as a parameter.
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
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With