ViewModel如何保留数据?
视图模型如何保留由于配置而导致的数据,而当我们尝试重新实例化活动时,如何保留数据。
查看模型对象在获取ViewModel时将其范围传递给ViewModelProvider的生命周期。 ViewModel保留在记忆中,直到生命周期范围范围范围范围oppoper
viewModel = ViewModelProviders.of(this)[MainActivityViewModel::class.java]
在此处 这 是生命周期所有者MainActivity。
旋转/配置更改之前: 旋转/配置更改后:
我们可以在这里清楚地看到活动(所有者)和生命周期的实例正在旋转后发生变化。那么,为什么它仅在配置中保存数据会更改。同时,当我尝试手动创建同一活动的新实例以重新创建此方案时,视图模型没有保留数据。
视图模型的决定参数是什么以保留数据。
以及为什么ViewModel仅保留用于配置更改的数据,而不是与同一活动的新实例之类的东西保留。
How can viewModel retains data due to configuration changes but not when we try to re instantiate the activity.
ViewModel objects are scoped to the Lifecycle passed to the ViewModelProvider when getting the ViewModel. The ViewModel remains in memory until the Lifecycle it's scoped to goes away permanently
viewModel = ViewModelProviders.of(this)[MainActivityViewModel::class.java]
Here this is the lifecycle owner MainActivity.
Before rotation/ config change:
After rotation/ config change:
We can clearly see here that instance of activity (owner) and lifecycle are changing after rotation. So why its saving the data only in configuration changes. Meanwhile when i tried creating a new instance of same activity manually to re create this scenario the view model is not retaining the data.
What are the deciding parameters for view model to retain the data or not.
And why viewModel retains the data only for config changes and not for something like new instance of same activity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
构建器内部活动/片段的生命周期上有一个观察者。
组件性是片段和appCompactactivity的母体类别。
每次都会触发它的生命周期回电,并且如果其onDestroy()呼叫,如果它不是配置更改,则它将清除ViewModelStore。
因此,决定参数为 iSchangingConfigurations()
There is an observer set on the lifecycle of activity/ fragment inside ComponentActivity constructor.
ComponentActivity is the parent class of Fragment and AppCompactActivity.
It'll be triggered everytime a lifecycle call back is made and if its onDestroy() callback and if its not a configuration change only then it will clear the viewModelStore.
so the deciding parameter is isChangingConfigurations()