Search code examples
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:

    • An unhandled exception
    • The user clicking "Force Stop" on your app's screen in the Settings app
    • Some cases where the system terminates your process in the background (specifically, where the need for system RAM is urgent, such as to handle an incoming call, and your app's process "draws short straw" to be terminated)

    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.