Dali Szilard Dali Szilard - 6 months ago 36
Android Question

Android form validation using reactive programming

I'm fairly new to RxJava, RxAndroid. I have two

one for password and one for password confirmation. Basically I need to check if the two strings match. Is it possible to do this using
? Would really appreciate an example so I can grasp it. Cheers.

Answer Source

First, create Observable out of your EditText. You can utilize RxBinding library or write wrappers by yourself.

Observable<CharSequence> passwordObservable = 
Observable<CharSequence> confirmPasswordObservable = 

Then merge your streams and validate values using combineLatest operator:

Observable.combineLatest(passwordObservable, confirmPasswordObservable, 
    new BiFunction<CharSequence, CharSequence, Boolean>() {
        public Boolean apply(CharSequence c1, CharSequence c2) throws Exception {
            String password = c1.toString;
            String confirmPassword = c2.toString;
            // isEmpty checks needed because RxBindings textChanges Observable
            // emits initial value on subscribe
            return !password.iEmpty() && !confirmPassword.isEmpty() 
                                      && password.equals(confirmPassword);
    .subscribe(new Consumer<Boolean>() {
        public void accept(Boolean fieldsMatch) throws Exception {
             // here is your validation boolean!
             // for example you can show/hide confirm button
             if(fieldsMatch) showConfirmButton();
             else hideCOnfirmButton();
    }, new Consumer<Throwable>() {
        public void accept(Throwable throwable) throws Exception {
            // always declare this error handling callback, 
            // otherwise in case of onError emission your app will crash
            // with OnErrorNotImplementedException

subscribe method returns Disposable object. You have to call disposable.dispose() in your Activity's onDestroy callback (or OnDestroyView if you are inside Fragment) in order to avoid memory leaks.

P.S. The example code uses RxJava2

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download