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
If you create a variable say
var a = 10
inFragment
orActivity
, then you change it somewhere (ex: a button click), now it becomes50
, then you rotate the screen (known as Configuration Change), you will notice thata
becomes10
again. Sounds bothering sometimes huh?ViewModel
is designed for solving this problem.Of course you must extend (inherit) your class from
ViewModel
orAndroidViewModel
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:
Rotate screen
Change system language
Plug in physical keyboard
Connected to a mouse
KEY POINT: After configuration change, Activity will be recreated, thus data might be lost.