ViewModel vs static variable in an activity

Viewed 1755

I know that one of the solutions to handle orientation change is to use ViewModel to hold the data as it outlives the activity.

However, I was wondering, can't we achieve the same thing if we create a static variable in the class to hold the same data?

Why would we go down the ViewModel path?

Thanks

4 Answers

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.

Static variable will always exist throughout the lifecycle of the application. If you don't clean it up in time, memory may be wasted.

ViewModel library in one of the Android architecture components and apart from handling configuration changes, it also acts as a mode of communication between Activity/Fragment and data access layer of your application. This data access layer may include your cache, SQLite or any other remote data over cloud. Associating ViewModel with LiveData can do lot of other things. Refer to a sample here.

Related