Last active
June 19, 2022 17:20
-
-
Save Skyyo/7968b89a71d85468938992b9fe4f660f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private class InputErrors( | |
val nameErrorId: Int?, | |
val cardErrorId: Int? | |
) | |
@HiltViewModel | |
class FormValidationViewModel @Inject constructor(..) : ViewModel() { | |
fun onNameEntered(input: String) { | |
handle[NAME] = name.value.copy(value = input, errorId = null) | |
} | |
fun onContinueClick() { | |
viewModelScope.launch(Dispatchers.Default) { | |
when (val inputErrors = getInputErrorsOrNull()) { | |
null -> { | |
clearFocusAndHideKeyboard() | |
_events.send(ScreenEvent.ShowToast(R.string.success)) | |
} | |
else -> displayInputErrors(inputErrors) | |
} | |
} | |
} | |
private fun getInputErrorsOrNull(): InputErrors? { | |
val nameWrapper = name.value | |
val cardWrapper = creditCardNumber.value | |
val nameErrorId = InputValidator.getNameErrorIdOrNull(nameWrapper.value) | |
val cardErrorId = InputValidator.getCardNumberErrorIdOrNull(cardWrapper.value) | |
return if (nameErrorId == null && cardErrorId == null) { | |
null | |
} else { | |
InputErrors(nameErrorId, cardErrorId) | |
} | |
} | |
private suspend fun displayInputErrors(inputErrors: InputErrors) { | |
handle[NAME] = name.value.copy(errorId = inputErrors.nameErrorId) | |
handle[CREDIT_CARD_NUMBER] = creditCardNumber.value.copy(errorId = inputErrors.cardErrorId) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment