2017-08-24 5 views
1

私はRxJava、RxAndroidをかなり使い慣れています。私は2つのeditTextパスワード用とパスワード確認用の2つがあります。基本的には、2つの文字列が一致するかどうかを確認する必要があります。これはObservablesを使用して可能ですか?私はそれをつかむことができるので、例を本当に感謝します。乾杯。リアクティブプログラミングを使用したAndroidフォームの検証

+0

一般的なアプローチは何ですか?編集テキストの変更に反応して反応したいのですか、または検証結果に反応するビューを使用しますか? –

答えて

0

まず、あなたの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コールバック(Fragmentの場合はOnDestroyView)にdisposable.dispose()と電話する必要があります。

P.S.サンプルコードで使用するRxJava2

0

thisライブラリを使用すると、このようなことができます。

Observable 
      .combineLatest(RxTextView.textChanges(passwordView1), 
          RxTextView.textChanges(passwordView2), 
          (password1, password2) -> checkPasswords)) 
      .filter(aBoolean -> aBoolean) 
      .subscribe(aBoolean -> Log.d(passwords match)) 
関連する問題