Basically, I have a UI state data class as:
data class ServerState(
val isLoading: Boolean = true,
val fileData: MainData? = null,
val error: Throwable? = null,
)
In my ViewModel
there are two types of errors. First, is if the client
is unreachable I show a full screen error with the text.
Now If someone tries to use another method it will also give an Exception
, like for a single POST method. I want to show a Toast
for that exception without passing context to the ViewModel
.
For eg, this is a method in my ViewModel
:-
private val _uiState = MutableStateFlow(ServerState())
val uiState = _uiState.asStateFlow()
fun addFile(bytes: ByteArray) {
viewModelScope.launch {
when (
val result: Result<Unit, Throwable> = runCatching {
client.add { rawFile["file_test"] = bytes }
}
) {
is Ok -> return@launch
is Err -> emitException(result.error)
}
}
}
private fun emitException(e: Throwable) {
val error = ExceptionHandler.mapException(e)
_uiState.update { state -> state.copy(error = error) }
}
I basically want to only show the major errors on full screen and minor method errors as Toast
. Should I just add fields inside the state for it?
How should I approach this?
CodePudding user response:
For different UI behaviour just add another state. 2 different states will be handled at UI. 1 for full screen errors and another for Toasts.