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
@HiltViewModel | |
class InputValidationAutoViewModel @Inject constructor( | |
private val savedStateHandle: SavedStateHandle | |
) : ViewModel() { | |
val name = handle.getStateFlow(NAME, InputWrapper()) | |
val creditCardNumber = handle.getStateFlow(CREDIT_CARD_NUMBER, InputWrapper()) | |
val areInputsValid = combine(name, creditCardNumber) { name, cardNumber -> | |
name.value.isNotEmpty() && name.errorId == null && cardNumber.value.isNotEmpty() && cardNumber.errorId == null | |
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), false) | |
private val _events = Channel<ScreenEvent>() | |
val events = _events.receiveAsFlow() | |
fun onNameEntered(input: String) { | |
val errorId = InputValidator.getNameErrorIdOrNull(input) | |
handle[NAME] = name.value.copy(value = input, errorId = errorId) | |
} | |
fun onCardNumberEntered(input: String) { | |
val errorId = InputValidator.getCardNumberErrorIdOrNull(input) | |
handle[CREDIT_CARD_NUMBER] = creditCardNumber.value.copy(value = input, errorId = errorId) | |
} | |
fun onContinueClick() { | |
viewModelScope.launch(Dispatchers.Default) { | |
val resId = if (areInputsValid.value) R.string.success else R.string.validation_error | |
_events.send(ScreenEvent.ShowToast(resId)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment