androidviewmodelandroid-lifecycleandroid-viewmodel

Is onCleared guarranteed to be called on a ViewModel in android?


Can I safely put code to persist viewmodel data in the viewmodel's onCleared method? Would that guarrantee that the viewmodel's data will be put in persistant storage if the app is killed or finished for any reason or are there cases where onCleared may not be called?


Solution

  • are there cases where onCleared may not be called?

    At minimum, it would be the cases where onDestroy() on an Activity may not be called. That includes:

    Also note that while system BACK navigation usually destroys an activity, that is not guaranteed. In particular, on Android 12 and higher, system BACK navigation from the root activity does not destroy the activity. Since the activity is not destroyed, onCleared() will not be called.

    So, usually onCleared() is called, but it is not guaranteed.