So i’m curious how you can create a view model bac...
# compose
m
So i’m curious how you can create a view model backed by MutableState but still be able to have the data saved to the savedStateHandle. With livedata i could just back the entire property by the saved state handle, assuming the value was parcelable.
Copy code
data class UIState(val startTime: Long = System.currentTimeMillis())

class UIStateVM(savedStateHandle: SavedStateHandle): ViewModel() {
    private val _uiState = mutableStateOf(UIState())
    val uiState: State<UIState> get() = _uiState
}
I could do this manually, but it seems like there should be a better way:
Copy code
init {
        savedStateHandle.get<UIState>("uiState")?.let { state ->
            _uiState.value = state
        }
        viewModelScope.launch {
            snapshotFlow { uiState.value }.collect { state ->
                savedStateHandle.set("uiState", state)
            }
        }
    }
a
There currently isn’t a better built-in way, unfortunately. A complete solution would also likely take advantage of the
Saver
interface from Compose. You can follow https://issuetracker.google.com/issues/195689777 for any updates around this area.
i
Have you looked at SavedStateHandle's support for non-parcelable classes? That seems like exactly what you need: https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate#non-parcelable
k
I’m not sure if it’s what you’re looking for, but this article presents an interesting solution to connect
SavedStateHandle
with
MutableState