【问题标题】:Android form validation using reactive programming使用响应式编程的 Android 表单验证
【发布时间】:2017-08-24 09:23:08
【问题描述】:

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

【问题讨论】:

  • 您的一般做法是什么?您想对编辑文本中的更改做出反应性反应,还是希望对验证结果做出反应?

标签: android forms rx-java observable rx-android


【解决方案1】:

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

P.S.示例代码使用RxJava2

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多