0. 目录
- 简介
- 好处
- GitHub 地址
- 依赖
- 示例
1. 简介
RxBinding 是 Jake Wharton 写的框架,它的 Api 能够把 Android 平台和兼容包内的 UI 控件变为 Observable 对象,这样就可以把 UI 控件的事件当做 Rxjava 中的数据流来使用了.
2. 好处
- 能对 View 事件使用 Rxjava 的各种操作.
- 提供了与 Rxjava 一致的回调,代码简洁明了.
- 几乎支持所有的常用控件和事件.
- 每个库还有对应的 Kotlin 支持库.
3. GitHub 地址
https://github.com/JakeWharton/RxBinding/
4. 依赖
implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
5. 示例
用标准简洁的实现方式,作用于整个App的所有UI事件.
- 点击事件:
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO
}
});
RxView.clicks(button)
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
// TODO
}
});
- 文本输入
EditText editText = findViewById(R.id.editText);
editText.addTextChangedListener(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) {
// TODO
}
@Override
public void afterTextChanged(Editable s) {
}
});
RxTextView.textChanges(editText)
.subscribe(new Consumer<CharSequence>() {
@Override
public void accept(CharSequence charSequence) throws Exception {
// TODO
}
});
- 长点击事件:
RxView.longClicks(button).subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
}
// TODO
});
- 防止重复点击(弱网络环境下):
加入依赖:
implementation 'com.safframework:saf-rxlifecycle:1.0.0'
RxView.clicks(button)
.compose(useRxViewTransformer(this))
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
// TODO
}
});
/**
* 绑定内存泄漏,解决Rxjava内存泄漏的问题
* @param targetActivity
* @return
*/
public ObservableTransformer useRxViewTransformer(final AppCompatActivity targetActivity) {
return new ObservableTransformer() {
@Override
public ObservableSource apply(Observable upstream) {
return upstream.compose(preventDuplicateClicksTransformer())
.compose(RxLifecycle.bind(targetActivity).toLifecycleTransformer());
}
};
}
/**
* 防止重复点击
*
* @return
*/
public static ObservableTransformer preventDuplicateClicksTransformer() {
return new ObservableTransformer() {
@Override
public ObservableSource apply(Observable upstream) {
return upstream.throttleFirst(1000, TimeUnit.MICROSECONDS);
}
};
}
说明:
① Android App 使用Rxjava 存在一个缺点: 不完整的订阅会导致内存泄漏.
② 当Observable 正在运行,Activity或Fragment 销毁后,其观察者仍然会持有对它的引用,系统无法对此Activity/Fragment 进行垃圾回收.
③ RxLifecycle 可以通过绑定声明周期的方式,来解决内存泄漏的问题.
- 验证码倒计时:
RxView.clicks(button)
.throttleFirst(MAX_COUNT_TIME, TimeUnit.SECONDS)
.flatMap(new Function<Object, ObservableSource<Long>>() {
@Override
public ObservableSource<Long> apply(Object o) throws Exception {
// 更新发送按钮的状态,并初始化显示倒计时文字
RxView.enabled(button).accept(false);
RxTextView.text(button).accept("剩余" + MAX_COUNT_TIME + " 秒");
// 返回 n 秒内的倒计时观察者对象
return Observable.interval(1, TimeUnit.SECONDS, Schedulers.io())
.take(MAX_COUNT_TIME);
}
})
// 将递增数字替换成递减的倒计时数字
.map(new Function<Long, Long>() {
@Override
public Long apply(Long aLong) throws Exception {
return MAX_COUNT_TIME - (aLong + 1);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
if (aLong == 0){
RxView.enabled(button).accept(true);
RxTextView.text(button).accept("获取验证码");
}else{
RxTextView.text(button).accept("剩余"+aLong +" 秒");
}
}
});
- RecyclerView:
implementation 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.1.1'
// recycerview 当前没有滚动
private static final int SCROLL_STATE_IDLE = 0;
// recyclerview 正在被拖动
private static final int SCROLL_STATE_DRAGGING = 1;
// 手已经离开屏幕,recyclerview正在做动画移动到最终位置
private static final int SCROLL_STATE_SETTLING = 2;
RxRecyclerView.scrollStateChanges(recyclerView)
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer scrollState) throws Exception {
Log.d("state",scrollState.toString());
}
});
说明:
- RecyclerView 提供几个状态的观察.
① scrollStateChanges 观察 RecyclerView 的滚动状态.
② scrollEvents 观察 RecyclerView 的滚动事件.
③ childAttachStateChangeEvents 观察 child view 的 detached 状态 ,当 LayoutManager 或者 RecyclerView 认为不再需要一个 child view 时,就会调用这个方法. 如果child view 占用资源,则应当释放资源.
④ 以上的例子是 对 滚动状态的监听. - 以下是对RecyclerView 点击事件的监听:
@Override
protected void convert(ViewHolder holder, final String s, int position) {
holder.setText(R.id.text, s);
RxView.clicks(holder.itemView)
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
}
});
}
- 表单验证:
public class ValidationResult {
public boolean flag;
public String message;
public ValidationResult() {
flag = true;
message = "";
}
}
final Button button = findViewById(R.id.button);
final EditText edit02 = findViewById(R.id.editText2);
final EditText edit03 = findViewById(R.id.editText3);
Observable<CharSequence> observable_phone = RxTextView.textChanges(edit02);
Observable<CharSequence> observable_password = RxTextView.textChanges(edit03);
Observable.combineLatest(observable_phone, observable_password,
new BiFunction<CharSequence, CharSequence, ValidationResult>() {
@Override
public ValidationResult apply(CharSequence phone, CharSequence passwrod) throws Exception {
if (phone.length() > 0 && passwrod.length() > 0) {
button.setBackground(getResources().getDrawable(R.drawable.shape_login_pressed));
} else {
button.setBackground(getResources().getDrawable(R.drawable.shape_login_normal));
}
ValidationResult validationResult = new ValidationResult();
if (phone.length() == 0) {
validationResult.flag = false;
validationResult.message = "手机号码不能为空";
} else if (phone.length() != 11) {
validationResult.flag = false;
validationResult.message = "手机号码需要11位";
} else if (passwrod.length() == 0) {
validationResult.flag = false;
validationResult.message = "密码不能为空";
}
return validationResult;
}
}).subscribe(new Consumer<ValidationResult>() {
@Override
public void accept(ValidationResult validationResult) throws Exception {
mReslut = validationResult;
}
});
RxView.clicks(button)
.compose(useRxViewTransformer(this))
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(Object o) throws Exception {
if (mReslut == null) return;
if (mReslut.flag) {
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, mReslut.message, Toast.LENGTH_SHORT).show();
}
}
});
说明:
① combineLatest 的作用就是将过个Observable发射的数据组装起来然后再发射出来.
② 这里两个输入框只要内容发生变化,就会发送 Observable , 此时我们即可在 BiFunction 中利用验证方法去判断输入框中最新的内容,最终返回一个ValidationResult 对象.
6. 后续
如果大家喜欢这篇文章,欢迎点赞;如果想看更多 rxjava 方面的技术,欢迎关注!