I've extended the default failure/success validati...
# compose
r
I've extended the default failure/success validation to a pending one, because I'm validating via server - but I'm not sure how to wire everything up, so the previous validation gets cancelled when the next one fires.
Copy code
sealed interface RemoteValidationResult {
    data object Success : RemoteValidationResult
    data class Failure(val errorResource: StringResource) : RemoteValidationResult
    data class Pending(val loadingResource: StringResource) : RemoteValidationResult {
        val next: Channel<RemoteValidationResult> = Channel(1, BufferOverflow.DROP_OLDEST)
    }
}
And wiring it up as
Copy code
val (result, flow) = validate(viewModelScope, text)
validationJob?.cancel()
validationJob = viewModelScope.launch {
    if (result is RemoteValidationResult.Pending) {
        launch {
            result.next.consumeEach {
                _state.transformIf<Loaded> {
                    copy(validationResult = it)
                }
            }
        }
    }
}
I'm wondering if there's a better way to approach this
b
I find that method of maintaining state to be very cumbersome, it means you never know in you composition what kind of sate you are getting so you have to check everything. instead why not have a simple data class as your state? that way you don't need to switch on what type the state is. You can simply set up your current uiState the way you need for the current composition. data class MyUiState(val isValidatingRemotely = true, remoteValidationMessage = "What I'm doing right now") that way you only need to set up your state once and when they validation returns, you update teh state.
r
How would I cancel a running validation though?
I could be returning
Flow<RemoteValidationResult>
though and get rid of the
Channel
🤔
b
your VM us holding that channel isn't it? The state is independent, so if you initiated a new validation, you would just cancel the previous one. and the UI state would never have to know, or you could just reset it. The UIState only updates when one of those channels finishes.
that would work with your sealed class as well, since it should still be separate from the operation happening in the VM.
1. set your state to pending 2. initiate the validation operation. 3. update your state as appropriate when the validation returns.
or if you cancel the previous validation to run a new one, no need to change the state.