Skip to content

Instantly share code, notes, and snippets.

@Skyyo
Last active August 29, 2022 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Skyyo/c4e605b34ecd2e6aaa84982642859637 to your computer and use it in GitHub Desktop.
Save Skyyo/c4e605b34ecd2e6aaa84982642859637 to your computer and use it in GitHub Desktop.
@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