1.需求場(chǎng)景
需要同時(shí)對(duì)多個(gè)事件進(jìn)行聯(lián)合判斷康铭,如蹋宦,填寫(xiě)表單時(shí)披粟,需要表單里所有信息(姓名,年齡冷冗,職業(yè)等)都被填寫(xiě)后守屉,才允許點(diǎn)擊“提交”按鈕。
2.具體實(shí)現(xiàn)
采用操作符combineLatest實(shí)現(xiàn)上述功能蒿辙。
@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, "提交按鈕是否可點(diǎn)擊:" + b);
submit.setEnabled(b);
}
});
}
3.測(cè)試結(jié)果
07-03 17:57:03.175 19903-19903/? D/RxJava: 提交按鈕是否可點(diǎn)擊:true
參考文章: