I use the conventional way in ViewModel to store and restore the value
private val _stateFlow = MutableStateFlow(
savedStateHandle.get("key") ?: InitialValue
)
And when setting the value
_stateFlow.value = ChangeValue
savedStateHandle.set("key", ChangeValue)
Not ideal, but at least we have a way to save the latest value.
And thanks to https://www.reddit.com/user/coffeemongrul/, who provided a proposal to wrap it around with a class as per https://www.reddit.com/r/androiddev/comments/rlxrsr/in_stateflow_how_can_we_save_and_restore_android/
class MutableSaveStateFlow<T>(
private val savedStateHandle: SavedStateHandle,
private val key: String,
defaultValue: T
) {
private val _state: MutableStateFlow<T> =
MutableStateFlow(savedStateHandle.get<T>(key) ?: defaultValue)
var value: T
get() = _state.value
set(value) {
_state.value = value
savedStateHandle.set(key, value)
}
fun asStateFlow(): StateFlow<T> = _state
}