title: How to best clear an Android ViewModel when the app is killed?
body: <p>I am currently overriding <code>ViewModel.onCleared()</code> to clean up my ViewModel to prevent any leaks (in this case to remove any files from the app's internal storage that have not been used).</p>
  
  <p>That works totally fine when the ViewModel's activity is finished explicitly. But since <code>onDestroy()</code> is not called when the app is killed <code>onCleared()</code> is neither.</p>
  
  <p>My intention (at the moment) is not to save any data, I just don't want any data leaks, neither when the system kills my process nor when the user kills it.</p>
  
  <p><strong>What is working</strong></p>
  
  <ol>
  <li>The activity is started and the user takes a picture which is saved
  in the app's internal storage.</li>
  <li>The user leaves the activity without
  saving.</li>
  <li>The activity is destroyed and <code>ViewModel.onCleared()</code> is
  called which deletes the unused picture.</li>
  </ol>
  
  <p><strong>What is not working</strong> (but could be solved by using <code>Activity.onSaveInstanceState()</code></p>
  
  <ol>
  <li><p>The activity is started and the user takes a picture which is saved
  in the app's internal storage.</p></li>
  <li><p>The activity's process is killed by the system for whatever reason.</p></li>
  <li><p>Neither <code>Activity.onDestroy</code> nor <code>ViewModel.onCleared()</code> is called.</p></li>
  </ol>
  
  <p><strong>What is also not working</strong></p>
  
  <ol>
  <li><p>The activity is started and the user takes a picture which is saved
  in the app's internal storage.</p></li>
  <li><p>The user kills the app by swiping.</p></li>
  <li><p>Neither <code>Activity.onDestroy</code> nor <code>ViewModel.onCleared()</code> is called.</p></li>
  </ol>
  
  <p>I fear I will have to persist the file names that need to be cleaned up to solve the third case, but this feels very extreme and I was hoping that there was a more intelligent way using the lifecycle methods.</p>
  
  <p>Am I missing something?</p>