title: How to convert ViewModel to utilize state saving?
body: <p>I have a <code>ViewModel</code> I am currently using to contain data and share values between Fragments.  This model also helps instantiate the data for the app on activity start.</p>
  
  <p>I am now trying to add in state saving functionality to my app, and I'm confused on how to merge the two systems together.  The android docs mention to use this constructor:</p>
  
  <pre class="lang-java prettyprint-override"><code>public MyViewModel(SavedStateHandle savedStateHandle) {
      mState = savedStateHandle;
  }
  </code></pre>
  
  <p>However, I'm unsure on how the state is passed and how this constructor is used in activities (here is my usage):</p>
  
  <pre class="lang-java prettyprint-override"><code> myViewModel = new ViewModelProvider(requireActivity()).get(myViewModel.class);
  </code></pre>
  
  <p>Anyway, since I need to also instantiate data in case the savedState is null, I'm not sure how that part fits in.  For reference, here is a general outline of my ViewModel class:</p>
  
  <pre class="lang-java prettyprint-override"><code>public class myViewModel extends ViewModel {
  //    private MutableLiveData&lt;Integer&gt; foo;  &lt;-- obsolete with state saving
  
      private SavedStateHandle mState;
      private static final String FOO_KEY = "foo";
  
      // Do I need this anymore? How do I combine this with the other constructor?
      public myViewModel() {
          foo = new MutableLiveData&lt;&gt;();
          foo.setValue(4);
      }
  
      // Constructor for the savedStateHandle
      public myViewModel(SavedStateHandle savedStateHandle) { mState = savedStateHandle; }
  
      LiveData&lt;Integer&gt; getFoo() { return mState.getLiveData(FOO_KEY); }
  
      void setFoo(int foo) { mState.set(FOO_KEY, foo); }
  
  }
  </code></pre>
  
  <p>Obviously if I take out the old constructor and <code>MutableLiveData</code> member, then when I access the ViewModel in my fragments, the data will be null (because I haven't told the activity to explicitly save a state yet), and I haven't instantiated any data.</p>