Dali Szilard Dali Szilard - 1 month ago 8
Android Question

Android form validation using reactive programming

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

editText
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
Observables
? 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 = 
                      RxTextView.textChanges(passwordEditText);
Observable<CharSequence> confirmPasswordObservable = 
                      RxTextView.textChanges(confirmPasswordEditText);

Then merge your streams and validate values using combineLatest operator:

Observable.combineLatest(passwordObservable, confirmPasswordObservable, 
    new BiFunction<CharSequence, CharSequence, Boolean>() {
        @Override
        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>() {
        @Override
        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>() {
        @Override
        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
            throwable.printStackTrace();
        }
    });

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