title: Manually clearing an Android ViewModel?
body: <p><em>Edit:</em> This question is a bit out of date now that Google has given us the ability to scope <code>ViewModel</code> to navigation graphs. The better approach (rather than trying to clear activity-scoped models) would be to create specific navigation graphs for the right amount of screens, and scope to those.</p>
  
  <hr>
  
  <p>With reference to the <code>android.arch.lifecycle.ViewModel</code> class.</p>
  
  <p><code>ViewModel</code> is scoped to the lifecycle of the UI component it relates to, so in a <code>Fragment</code>-based app, that will be the fragment lifecycle. This is a good thing.</p>
  
  <hr>
  
  <p>In some cases one wants to share a <code>ViewModel</code> instance between multiple fragments. Specifically I am interested in the case where <em>many screens relate to the same underlying data</em>. </p>
  
  <p>(The docs suggest similar approach when multiple related fragments are displayed on the same screen but <a href="https://stackoverflow.com/a/53653341/383414">this can be worked around by using a single host fragment as per answer below</a>.)</p>
  
  <p>This is discussed in the <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModel" rel="noreferrer">official ViewModel documentation</a>:</p>
  
  <blockquote>
    <p>ViewModels can also be used as a communication layer between different
    Fragments of an Activity. Each Fragment can acquire the ViewModel
    using the same key via their Activity. This allows communication
    between Fragments in a de-coupled fashion such that they never need to
    talk to the other Fragment directly.</p>
  </blockquote>
  
  <p>In other words, to share information between fragments that represent different screens, the <code>ViewModel</code> should be scoped to the <code>Activity</code> lifecycle (and according to Android docs this can also be used in other shared instances).</p>
  
  <hr>
  
  <p>Now in the new Jetpack Navigation pattern, it is recommended to use a "One Activity / Many Fragments" architecture. This means that the activity lives for the whole time the app is being used. </p>
  
  <p>i.e. any shared <code>ViewModel</code> instances that are scoped to <code>Activity</code> lifecycle will never be cleared - the memory remains in constant use.</p>
  
  <p>With a view to preserving memory and using as little as required at any point in time, it would be nice to be able to clear shared <code>ViewModel</code> instances when no longer required.</p>
  
  <hr>
  
  <p>How can one manually clear a <code>ViewModel</code> from it's <code>ViewModelStore</code> or holder fragment?</p>