gpt4 book ai didi

android - 如何懒惰地保存 ViewModel 的 SavedStateHandle?

转载 作者:行者123 更新时间:2023-12-04 01:19:41 25 4
gpt4 key购买 nike

我有一个加载一堆请求的屏幕,并在同一屏幕和一个外部 WebView 上从用户那里收集一些数据。因此,我有一个包含这些复杂请求对象(+ 用户输入数据)的 ViewModel。我需要通过系统启动的进程死亡来保存这些数据,SavedStateHandle专为。但我不想将这些数据保存在数据库中,因为它只与当前的用户体验相关。
我已将我的 ViewModel 与 Hilt 集成并收到 SaveStateHandle .因为我有一些复杂的对象可以在代码中的多个位置访问/修改,所以我无法“随时随地”保存它们。我让他们实现了Parcelable只是想立即拯救他们。不幸的是,ViewModel 没有像 onSaveInstanceState() 这样的生命周期方法。 .
现在,我尝试使用 onCleared()这听起来像是写到句柄的好地方。但事实证明,所有 .set()我在那里执行的操作会丢失(我正在使用开发人员选项“不要保留 Activity ”进行测试。当我在其他地方使用 .set() 时,它确实有效)。因为 ViewModel 不绑定(bind)到单个 fragment/Activity 的生命周期,而是绑定(bind)到 NavGraph,我无法从他们的 onSaveInstanceState() 调用.
我如何/在哪里可以正确地将我的状态保存在 SaveStateHandle 中?

最佳答案

这正是 Lifecycle 2.3.0-alpha03 release 的用例。启用:

SavedStateHandle now supports lazy serialization by allowing you to call setSavedStateProvider() for a given key, providing a SavedStateProvider that will get a callback to saveState() when the SavedStateHandle is asked to save its state. (b/155106862)


这使您可以处理任何复杂的对象并在需要保存时准确地获取回调。
var complexObject: ComplexObject? = null

init {
// When using setSavedStateProvider, the underlying data is
// stored as a Bundle, so to extract any previously saved value,
// we get it out of the Bundle, if one exists
val initialState: Bundle = savedStateHandle.get<Bundle?>("complexObject")
if (initialState != null) {
// Convert the previously saved Bundle to your ComplexObject
// Here, it is a single Parcelable, so we'll just get it out of
// the bundle
complexObject = initialState.getParcelable("parcelable")
}

// Now to register our callback for when to save our object,
// we use setSavedStateProvider()
savedStateHandle.setSavedStateProvider("complexObject") {
// This callback requires that you return a Bundle.
// You can either add your Parcelable directly or
// skip being Parcelable and add the fields to the Bundle directly
// The key is that the logic here needs to match your
// initialState logic above.
Bundle().apply {
putParcelable("parcelable", complexObject)
}
}
}

关于android - 如何懒惰地保存 ViewModel 的 SavedStateHandle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62800028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com