Search code examples
androidandroid-lifecycleandroid-viewmodel

How to best clear an Android ViewModel when the app is killed?


I am currently overriding ViewModel.onCleared() 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).

That works totally fine when the ViewModel's activity is finished explicitly. But since onDestroy() is not called when the app is killed onCleared() is neither.

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.

What is working

  1. The activity is started and the user takes a picture which is saved in the app's internal storage.
  2. The user leaves the activity without saving.
  3. The activity is destroyed and ViewModel.onCleared() is called which deletes the unused picture.

What is not working (but could be solved by using Activity.onSaveInstanceState()

  1. The activity is started and the user takes a picture which is saved in the app's internal storage.

  2. The activity's process is killed by the system for whatever reason.

  3. Neither Activity.onDestroy nor ViewModel.onCleared() is called.

What is also not working

  1. The activity is started and the user takes a picture which is saved in the app's internal storage.

  2. The user kills the app by swiping.

  3. Neither Activity.onDestroy nor ViewModel.onCleared() is called.

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.

Am I missing something?


Solution

  • Apparently it is not possible to make sure that ViewModel.onCleared() is called under all circumstances.

    I solved my specific problem by saving the files first into the cache directory and moving them to my image directory only if it is confirmed that they are needed. This way there still is a way to clean up any left over files in the cache if one of the edge cases occurs.