1.需求场景
需要同时对多个事件进行联合判断,如,填写表单时,需要表单里所有信息(姓名,年龄,职业等)都被填写后,才允许点击“提交”按钮。
2.具体实现
采用操作符combineLatest实现上述功能。
@BindView(R.id.name)
EditText name;
@BindView(R.id.age)
EditText age;
@BindView(R.id.job)
EditText job;
@BindView(R.id.submit)
Button submit;
@SuppressLint("CheckResult")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joint_judgment);
ButterKnife.bind(this);
final Observable<CharSequence> nameObservable = RxTextView.textChanges(name).skip(1);
Observable<CharSequence> ageObservable = RxTextView.textChanges(age).skip(1);
Observable<CharSequence> jobObservable = RxTextView.textChanges(job).skip(1);
Observable.combineLatest(nameObservable, ageObservable, jobObservable, new Function3<CharSequence, CharSequence, CharSequence, Boolean>() {
@Override
public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws Exception {
boolean isUserNameValid = !TextUtils.isEmpty(name.getText());
boolean isUserAgeValid = !TextUtils.isEmpty(age.getText());
boolean isUserJobValid = !TextUtils.isEmpty(job.getText());
return isUserNameValid && isUserAgeValid && isUserJobValid;
}
}).subscribe(new Consumer<Boolean>() {
@Override
public void accept(Boolean b) throws Exception {
Log.d(Constant.TAG, "提交按钮是否可点击:" + b);
submit.setEnabled(b);
}
});
}
3.测试结果
07-03 17:57:03.175 19903-19903/? D/RxJava: 提交按钮是否可点击:true
参考文章:
网友评论