Ruben Quadros
12/05/2024, 6:06 PMBaseViewModel
but I'm getting the following:
Cannot use STATE as reified type parameter. Use a class instead
More details in 🧵Ruben Quadros
12/05/2024, 6:07 PMabstract 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 mentionedRuben Quadros
12/05/2024, 6:26 PMserializer: KSerializer<STATE>
and use it via
savedStateHandle.saved(
key = "SAVED_STATE",
serializer = serializer
){ initialState }