Why we need to extend ```ViewModel()``` for DataBinding and LiveData to create LiveData object

877 Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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.