Skip to content

Instantly share code, notes, and snippets.

@Tanapruk
Last active August 31, 2016 07:00
Show Gist options
  • Save Tanapruk/49bab8e9a37ec5649914364afeb2ee70 to your computer and use it in GitHub Desktop.
Save Tanapruk/49bab8e9a37ec5649914364afeb2ee70 to your computer and use it in GitHub Desktop.
RxBinding

###Validate Your Login Email & Password With RxBinding and Kotlin

Variables

val emailChgObs = RxTextView.textChangeEvents(etEmail).publish().autoConnect(2)
val pwdChgObs = RxTextView.textChangeEvents(etPassword)

btnLogin.isEnabled = false

var subscriptionEmailValid = emailChgObs
                .filter { it.text().length > 4 }
                .debounce(400, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map { it.text().isEmail() }
                .subscribe { showError(it) }

var subscriptionEmailPwdFilled = Observable
                .combineLatest(emailChgObs, pwdChgObs) {
                    tvEmail, tvPwd ->
                    validateInputFilled(tvEmail.text().toString(), tvPwd.text().toString())
                }
                .subscribe { btnLogin.isEnabled = it }

####Methods

fun CharSequence.isEmail() = this.matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+".toRegex())

fun validateInputFilled(email: String, password: String) = email.isNotEmpty() && password.isNotEmpty()

fun showError(isEmail: Boolean) {
        etEmail.error = if (isEmail) null else "Invalid Email"
}

###Requirement

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment