How does the Android Viewmodel works internally?
How Viewmodel save the data when the activity gets destroyed and recreated when the device get rotated
How does the Android Viewmodel works internally?
Android's ViewModel
is designed to store and manage UI-related data in such a way that it can survive configuration changes such as screen rotations.
ViewModel
gets called by an activity that previously called it, it re-uses the instance of that ViewModel
object. However, if the Activity
gets destroyed or finished, counterpart ViewModel
calls the onClear()
method for clearing up resources. Meaning if you have added something like this to your ViewModel
:
override fun onClear() {
super.onClear()
clearAllLiveDataValues()
disposeAllVariables()
}
Function calls added here will be invoked.
How Viewmodel save the data when the activity gets destroyed and recreated when the device get rotated
ViewModel
has its own lifecycle that allows itself to recover its state, and the transient data it holds, during screen rotations.
NOTE:
Activity
andViewModel
's lifecycle are both ephemeral. Allowing theViewModel
to handle critical or sensitive data during configuration changes IS NOT RECOMMENDED .
Your application should use either shared prefs, secured storage (if necessary), local database or cloud storage when you are expected to handle critical or sensistive data in a specific screen or part of your app.
I recommend that you read the following:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.