ViewModel vs static variable in an activity

One reason is because Activities themselves aren't static or singletons. You can have an ItemViewActivity launch another ItemViewActivity for a different item, and if they're sharing the same variables via statics you've probably just broke the back button. And if you don't code them very carefully you're probably going to send data to the wrong Activity's views.


Good question! So, could we achieve the same? Probably yes, but it will be like re-inventing the wheel, and also you'll most likely end up into the same, or a similar, solution as the ViewModel provides. What I guess you need to understand here is that activities in Android are reflections of an underlying MVC design, whereas the data information you bind to your activities are decoupled from the view themselves, so that at any point in time you can re-bind your actual data state to the view (the activity) recreating it, and therefore continuing like nothing was changed. For instance upon a screen rotation, where your activity (view) is destroyed, given its data state is saved and passed, and then recreated, its data re-binded and user can continue from where she left. That's what ViewModel does, it manages the activity data state in the context of Android lifecycle. If you would like to accomplish the same yourself, it will be very difficult but possible.

Tags:

Android