(二)RxJava+RxBinding在View上的一些使用技巧

时间:2023-01-29 17:21:44
博客首页
            
    1、View防止连续点击Demo        不多说,很常用的功能          throttleFirst操作符:仅发送指定时间段内的第一个信号
RxView.clicks(btn_click)
.throttleFirst(3, TimeUnit.SECONDS)
.subscribe(new Action1<Void>() {
@Override
public void call(Void aVoid) {
Toast.makeText(getActivity(), R.string.des_demo_not_more_click, Toast.LENGTH_SHORT).show();
}
});

    2、CheckBox状态更新相关Demo            (1) 设置界面某项功能被打开或关闭,在SharedPreferences中存储对应的开关标记,方便其他地方读取             注:需要RxSharedPreferences库支持:https://github.com/f2prateek/rx-preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
RxSharedPreferences rxPreferences = RxSharedPreferences.create(preferences);
Preference<Boolean> xxFunction = rxPreferences.getBoolean("xxFunction", false);

checkBox1.setChecked(xxFunction.get());

RxCompoundButton.checkedChanges(checkBox1)
.subscribe(xxFunction.asAction());
        (2)在用户登录界面时,如果用户未勾选同意用户协议,不允许登录
RxCompoundButton.checkedChanges(checkBox2)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
btn_login.setClickable(aBoolean);
btn_login.setBackgroundResource(aBoolean ? R.color.can_login : R.color.not_login);
}
});
效果图如下: (二)RxJava+RxBinding在View上的一些使用技巧
3、搜索关键字提醒     搜索的关键字提醒功能,RxJava实现方式是如此的小清新。
        debounce操作符:     (二)RxJava+RxBinding在View上的一些使用技巧
RxTextView.textChangeEvents(et_search)
.debounce(300, TimeUnit.MILLISECONDS) //debounce:每次文本更改后有300毫秒的缓冲时间,默认在computation调度器
.observeOn(AndroidSchedulers.mainThread()) //触发后回到Android主线程调度器
.subscribe(new Action1<TextViewTextChangeEvent>() {
@Override
public void call(TextViewTextChangeEvent textViewTextChangeEvent) {
String key = textViewTextChangeEvent.text().toString().trim();
if (TextUtils.isEmpty(key)) {
iv_x.setVisibility(View.GONE);
if (mAdapter != null) {
mAdapter.clear();
mAdapter.notifyDataSetChanged();
}
} else {
iv_x.setVisibility(View.VISIBLE);
getKeyWordFormNet(key)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<String>>() {
@Override
public void call(List<String> strings) {
initPage(strings);
}
});
}
}
});
此处有些小问题:可以看到代码在获取到用户输入的字符后,便通过getKeyWordFromNet()方法拉去服务器匹配到的关键字,但这里明显是在RxJava中嵌套了RxJava代码,违背了Rxjava链式编程的初衷,本人第一时间想到用flatMap操作符进行转换链接,可flatMap中的call方法始终没有执行,诺有大神另有其他解决方案,还望给小弟解惑)

效果图如下: (二)RxJava+RxBinding在View上的一些使用技巧 (二)RxJava+RxBinding在View上的一些使用技巧




源码: https://github.com/cn-ljb/rxjava_for_android