ViewModel in kotlin

abhinesh chandra
2 min readSep 17, 2022

--

  • Suppose you have an activity that contains a random function that displays a random number.
  • Now when you rotate the device, configuration change happens and activity is destroyed and the random function is called again which generates the new no. Hence we can say that old data is not getting preserved.
  • To preserve old data we can use ViewModel.
  • ViewModel calls random func and provides the data to the activity in portrait mode.
  • When the configuration changes, ViewModel provides the saved data to the landscape mode without generating the new data.

ViewModel Scope

  • As you can see in the above picture, ViewModel gets attached to the activity as soon as it is created.
  • When the device is rotated ViewModel is still attached and updates UI with saved data.
  • When the user presses the back button activity is destroyed and along with it the ViewModel attached to it is also destroyed using onCleared() method.

Importance of ViewModel

  • When the activity is created, it has to handle different tasks like — displaying UI data, reacting to a user's actions, handle os communication, etc.
  • Doing this all operations in the activity makes the code complex and difficult to maintain.
  • We can do all these operations inside a ViewModel, which will make the code readable and maintainable. We can create an abstract class for ViewModel and then implement it for more readability.
  • In short, ViewModel handles all the data related to the view.
  • Api will not get called to fetch user data again on configuration change.

ViewModel Summary

  • Survives configuration changes. ex — Screen Rotation
  • Not same as onSaveInstanceState(). It is used to store small data like — string, integer, and boolean.
  • Used for large data such as a bitmap or user list.
  • Store and manage UI-related data
  • Destroyed only if owner Activity is completely destroyed, in onCleared().
  • Communication layer in between DB and UI.

--

--