Why should I use ViewModel?
Suppose I have an activity. I have a presenter class of this activity (MVP design pattern) from which I am downloading data from server. But before getting data from server, unfortunately I rotated the phone.
What will happen now? Activity will be recreated, which means the presenter object will be recreated.
Here again for getting data, presenter will call server API second time.
For worst scenario, assume you have an activity. From that activity you have started an asynchtask to perform long running operation. But before completion of this long running operation you have rotated the screen, boom!
What will happen in this case? Asynchtask will not stop, it will hold the reference of the destroyed activity. This will leak memory, but wait there is one more dangerous things remaining to happen. After performing that long running operation, asynchtask will try to update the UI of activity. But the reference of the activity which the asynctask is holding has been already destroyed. This will crash application with with message “java.lang.IllegalStateException: Activity has been destroyed”.
One more use case, as we know UI controllers such as activities and fragments are primarily intended to display UI data, react to user actions or handling OS communication such as permission request. But if you use these UI controllers to load data from a database or server, it will make the class complex. Assigning excessive work to the UI contoller in this way also makes testing a lot harder.
Now here comes the ViewModel for rescue from above mentioned issues.
What is ViewModel ?
ViewModel class is an Android Architecture Component.It is designed to store and manage UI-related data in a lifecycle conscious way. It allows data to survive configuration changes such as screen rotations.