Hey everyone! I want to save my state in a saved s...
# multiplatform
r
Hey everyone! I want to save my state in a saved state handle on every state update. I'm trying to do it via a
BaseViewModel
but I'm getting the following:
Copy code
Cannot use STATE as reified type parameter. Use a class instead
More details in 🧵
Copy code
abstract class BaseViewModel<STATE>(private val savedStateHandle: SavedStateHandle, private val initialState: Any): ViewModel() {

    private val _uiState: MutableStateFlow<STATE> = MutableStateFlow(getOrCreateInitialState())
    val uiState: StateFlow<STATE> = _uiState.asStateFlow()

    fun updateState(reducer: () -> STATE) {
        _uiState.update {
            val newState = reducer()
            savedStateHandle["SAVED_STATE"] = newState
            newState
        }
    }

    private fun getOrCreateInitialState(): STATE {
        val savedState by savedStateHandle.saved(key = "SAVED_STATE") { initialState }
        @Suppress("UNCHECKED_CAST") //intentional to throw exception if type is mismatched
        return savedState as STATE
    }
}
I do not want the
initialState
to be of type Any. I want to it to be of type STATE. But if I do that, I get the error that I mentioned
One way would be to also pass
serializer: KSerializer<STATE>
and use it via
Copy code
savedStateHandle.saved(
            key = "SAVED_STATE",
            serializer = serializer
        ){ initialState }