取資料先檢查快取的場景
取資料,首先檢查記憶體是否有快取
然後檢查檔案快取中是否有
最後才從網路中取
前面任何一個條件滿足,就不會執行後面的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
final Observable memory = Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber super String> subscriber) { if (memoryCache != null) { subscriber.onNext(memoryCache); } else { subscriber.onCompleted(); } } }); Observable disk = Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber super String> subscriber) { String cachePref = rxPreferences.getString("cache").get(); if (!TextUtils.isEmpty(cachePref)) { subscriber.onNext(cachePref); } else { subscriber.onCompleted(); } } }); Observable network = Observable.just("network"); //主要就是靠concat operator來實現 Observable.concat(memory, disk, network) .first() .subscribeOn(Schedulers.newThread()) .subscribe(s -> { memoryCache = "memory"; System.out.println("--------------subscribe: " + s); }); |
介面需要等到多個介面併發取完資料,再更新
1 2 3 4 5 6 7 8 9 |
//拼接兩個Observable的輸出,不保證順序,按照事件產生的順序傳送給訂閱者 private void testMerge() { Observable observable1 = DemoUtils.createObservable1().subscribeOn(Schedulers.newThread()); Observable observable2 = DemoUtils.createObservable2().subscribeOn(Schedulers.newThread()); Observable.merge(observable1, observable2) .subscribeOn(Schedulers.newThread()) .subscribe(System.out::println); } |
一個介面的請求依賴另一個API請求返回的資料
舉個例子,我們經常在需要登陸之後,根據拿到的token去獲取訊息列表。
這裡用RxJava主要解決巢狀回撥的問題,有一個專有名詞叫Callback hell
1 2 3 4 5 |
NetworkService.getToken("username", "password") .flatMap(s -> NetworkService.getMessage(s)) .subscribe(s -> { System.out.println("message: " + s); }); |
介面按鈕需要防止連續點選的情況
1 2 3 4 5 |
RxView.clicks(findViewById(R.id.btn_throttle)) .throttleFirst(1, TimeUnit.SECONDS) .subscribe(aVoid -> { System.out.println("click"); }); |
響應式的介面
比如勾選了某個checkbox,自動更新對應的preference
1 2 3 4 5 6 7 8 |
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); RxSharedPreferences rxPreferences = RxSharedPreferences.create(preferences); Preference checked = rxPreferences.getBoolean("checked", true); CheckBox checkBox = (CheckBox) findViewById(R.id.cb_test); RxCompoundButton.checkedChanges(checkBox) .subscribe(checked.asAction()); |
複雜的資料變換
1 2 3 4 5 6 7 |
Observable.just("1", "2", "2", "3", "4", "5") .map(Integer::parseInt) .filter(s -> s > 1) .distinct() .take(3) .reduce((integer, integer2) -> integer.intValue() + integer2.intValue()) .subscribe(System.out::println);//9 |