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

            

    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);
}
});
效果圖如下:

3、搜索關鍵字提醒
    搜索的關鍵字提醒功能,RxJava實現方式是如此的小清新。

        debounce操作符:    

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方法始終沒有執行,諾有大神另有其他解決方案,還望給小弟解惑)

效果圖如下:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章