RxJava实际应用--->联合判断


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 nameObservable = RxTextView.textChanges(name).skip(1);
        Observable ageObservable = RxTextView.textChanges(age).skip(1);
        Observable jobObservable = RxTextView.textChanges(job).skip(1);

        Observable.combineLatest(nameObservable, ageObservable, jobObservable, new Function3() {
            @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() {
            @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

参考文章:

  • Android RxJava 实际应用讲解:联合判断多个事件

你可能感兴趣的:(RxJava实际应用--->联合判断)