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:
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.