我正在使用android数据绑定,我想从编辑文本数据创建一个observable,所以我可以使用rxjava对它进行操作.这是我的代码.
XML
ViewModel类
public TextWatcher getUsername() { return new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.i("username", s.toString()); } @Override public void afterTextChanged(Editable s) { } }; }
我有3个这样的编辑文本,我想使用rx java的combinelatest运算符进行表单验证.我在这个场景中如何实现rx java?
您可以使用RxBinding.这个例子可以帮到你.
//Validate username field ObservableusernameObservable = RxTextView.textChanges(usernameEditText) .map(username -> StringUtils.isNotBlank(username) && Validators.validateUsername(username.toString())).skip(1); //Validate password field Observable passwordObservable = RxTextView.textChanges(passwordEditText).skip(1); //Validate confirm password field Observable confirmPasswordObservable = RxTextView.textChanges(confirmPasswordEditText) .skip(1); //Validate password matches field Observable passwordMatcherObservable = Observable.combineLatest(passwordObservable, confirmPasswordObservable, (password, confirmPassword) -> password.toString().equals(confirmPassword.toString())).skip(1); Observable.combineLatest(passwordMatcherObservable, usernameObservable, (passwordMatch, isUsernameValid) -> passwordMatch && isUsernameValid) .distinctUntilChanged() .subscribe(valid -> createAccountBtn.setEnabled(valid));