1

Without extending ViewModel() just with simple class I am able to implement LiveData and DataBinding example but I show in google developer doc to extend ViewModel() to create object of LiveData.So why we need to extend it?

https://developer.android.com/topic/libraries/architecture/livedata

Purvesh Dodiya
  • 594
  • 3
  • 17
  • 4
    You don't have to, but ViewModel makes life a lot easier. ViewModel keeps your data alive when the device has configuration changes, like the screen rotating. – Tenfour04 Apr 12 '21 at 13:24
  • 1
    Maybe take a look at the [documentation](https://developer.android.com/topic/libraries/architecture/viewmodel) for `ViewModel`? – Henry Twist Apr 12 '21 at 14:16

1 Answers1

5

If you create a variable say var a = 10 in Fragment or Activity, then you change it somewhere (ex: a button click), now it becomes 50, then you rotate the screen (known as Configuration Change), you will notice that a becomes 10 again. Sounds bothering sometimes huh? ViewModel is designed for solving this problem.

Any variable you declare inside ViewModel will not be affected by Configuration Change.

Of course you must extend (inherit) your class from ViewModel or AndroidViewModel to gain this ability. But If you don't need this feature, you don't need to extend them.


Following shows the cases which will lead to configuration change:

  1. Rotate screen

  2. Change system language

  3. Plug in physical keyboard

  4. Connected to a mouse

KEY POINT: After configuration change, Activity will be recreated, thus data might be lost.

Sam Chen
  • 7,597
  • 2
  • 40
  • 73