这正是Lifecycle 2.3.0-alpha03 版本启用的用例:
SavedStateHandle
现在通过允许您调用setSavedStateProvider()
给定的键来支持延迟序列化,提供一个SavedStateProvider
将在被要求保存其状态saveState()
时获得回调的 a。SavedStateHandle
( 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)
}
}
}