Instances of the new ViewModel
class can survive configuration changes if used in the following fashion:
mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
However, in addition to configuration changes, there is also a save-restore scenario when the entire application's process is being killed.
Will fields' values inside ViewModel
be preserved during save-restore scenario?
Edit: based on the answer to this question, I wrote this article: Android ViewModel Architecture Component is Dangerous
According to ViewModelProvider
documentation (check get
method), ViewModel
is not preserved when app's process is killed:
The created ViewModel is associated with the given scope and will be retained as long as the scope is alive (e.g. if it is an activity, until it is finished or process is killed)
In addition check Ian Lake answer to similar question: https://medium.com/@ianhlake/you-are-correct-the-viewmodel-is-destroyed-if-your-process-is-killed-by-android-ef611fcd51e6
You are correct: the ViewModel is destroyed if your process is killed by Android. Just like before, you should use onSaveInstanceState() to store any data you must have to later recreate your Activity in the same state as before.
I also recommend reading Android ViewModel Architecture Component is Dangerous.