RxBinding的使用场景
1.防止按钮重复点击,在1秒内只能响应点击一次
RxView.clicks(btn_test1)
.throttleFirst(1, TimeUnit.SECONDS)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1() {
@Override
public void call(Void aVoid) {
Log.e(TAG,"被点击一次-->,时间是:"+System.currentTimeMillis());
}
});
2.Buffer操作符,可以用来计算连续点击次数,使用share操作符(官方对share操作符的定义:返回一个新的Observable ,该Observable会广播给所有之前的。)
Observable clicks = RxView.clicks(btn_test2).share();
clicks.buffer(clicks.debounce(300,TimeUnit.MILLISECONDS))
.map(new Func1, Integer>() {
@Override
public Integer call(List voids) {
return voids.size();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1() {
@Override
public void call(Integer integer) {
btn_test2.setText(""+integer+"连击");
}
});
3.获取验证码,并倒计时
Observable voidObservable = RxView.clicks(btn_test3).throttleFirst(5, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Action1() {
@Override
public void call(Void aVoid) {
RxView.enabled(btn_test3).call(false);
}
});
voidObservable.subscribe(new Action1() {
@Override
public void call(Void aVoid) {
Observable.interval(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.take(5)
.subscribe(new Observer() {
@Override
public void onCompleted() {
RxTextView.text(btn_test3).call("获取验证码");
RxView.enabled(btn_test3).call(true);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long aLong) {
RxTextView.text(btn_test3).call("剩余" + (5 - aLong) + "秒");
}
});
}
});
4.监听EditText和CheckBox,全部勾选才点亮登录按钮
EditText et_user = (EditText) findViewById(R.id.et_user);
EditText et_password = (EditText) findViewById(R.id.et_password);
CheckBox cb_user = (CheckBox) findViewById(R.id.cb_user);
Observable userName = RxTextView.textChanges(et_user);
Observable passWord = RxTextView.textChanges(et_password);
Observable checkBox = RxCompoundButton.checkedChanges(cb_user);
Observable.combineLatest(userName, passWord, checkBox, new Func3() {
@Override
public Boolean call(CharSequence charSequence, CharSequence charSequence2, Boolean aBoolean) {
return charSequence.length()>0 && charSequence2.length()>0 && aBoolean;
}
}).subscribe(new Action1() {
@Override
public void call(Boolean aBoolean) {
RxView.enabled(btn_test4).call(aBoolean);
RxView.clicks(btn_test4).subscribe(new Action1() {
@Override
public void call(Void aVoid) {
Toast.makeText(MainActivity.this,"登录中...",Toast.LENGTH_SHORT).show();
}
});
}
});