Android 使用响应式编程进行表单验证

Android form validation using reactive programming

我是 RxJava、RxAndroid 的新手。我有两个 editText 一个用于密码,一个用于密码确认。基本上我需要检查两个字符串是否匹配。是否可以使用 Observables 来做到这一点?真的很感激一个例子,所以我可以掌握它。干杯。

您可以使用 this 库来做这样的事情。

  Observable
            .combineLatest(RxTextView.textChanges(passwordView1),
                          RxTextView.textChanges(passwordView2), 
                          (password1, password2) -> checkPasswords))
            .filter(aBoolean -> aBoolean)
            .subscribe(aBoolean -> Log.d(passwords match))

首先,从您的 EditText 中创建 Observable。您可以利用 RxBinding 库或自己编写包装器。

Observable<CharSequence> passwordObservable = 
                      RxTextView.textChanges(passwordEditText);
Observable<CharSequence> confirmPasswordObservable = 
                      RxTextView.textChanges(confirmPasswordEditText);

然后合并您的流并使用 combineLatest 运算符验证值:

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 方法 returns Disposable 对象。您必须在 ActivityonDestroy 回调中调用 disposable.dispose()(如果您在 Fragment 中,则调用 OnDestroyView)以避免内存泄漏。

P.S.示例代码使用RxJava2