Last active
August 29, 2022 10:17
-
-
Save Skyyo/c4e605b34ecd2e6aaa84982642859637 to your computer and use it in GitHub Desktop.
This file contains hidden or 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() { | |
val resId = if (areInputsValid.value) R.string.success else R.string.validation_error | |
_events.trySend(ScreenEvent.ShowToast(resId)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment