android - rxjava 條件判斷
問題描述
我想實現(xiàn)這樣一個功能,用戶點擊獲取數(shù)據(jù)庫數(shù)據(jù),若數(shù)據(jù)庫有這個數(shù)據(jù),則直接顯示本地的,若數(shù)據(jù)庫沒有這個數(shù)據(jù),就從服務器請求再顯示出來。請問一下用rxjava要怎么寫呢?
問題解答
回答1:1.先把功能函數(shù)寫出來.
private static Object loadFromCache(String key) { //....本地緩存加載,如果加載失敗返回 null } private static Object loadFromServer(String key) { //....通過網(wǎng)絡加載,返回數(shù)據(jù) Object obj = .... saveToCache(key, obj);//保存到本地緩存 return obj; }
2.將阻塞方法轉(zhuǎn)為RxJava的寫法
private static Observable<Object> rxLoadFromCache(String key) {return Observable.fromCallable(() -> loadFromCache(key)); } private static Observable<Object> rxLoadFromServer(String key) {return Observable.fromCallable(() -> loadFromServer(key)); }
3.合并到一起
public static Observable<Object> rxLoad(String key) {return Observable.concat(rxLoadFromCache(key),rxLoadFromServer(key)).filter(obj -> obj != null) .take(1); }
4.調(diào)用最后的方法
rxLoad(key) .subscribeOn(Schedulers.io()) .subscribe(obj->{ System.out.println(obj); });回答2:
Observable.concat(Observable.just(null), Observable.just(1)).filter(integer -> integer != null).take(1).subscribe(integer -> { //TODO});回答3:
Observable.if( () -> { return hasCache; }, Observable.just(cache), Observable.just(database),);
相關(guān)文章:
1. javascript - sublime快鍵鍵問題2. javascript - immutable配合react提升性能?3. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~4. javascript - nodejs關(guān)于進程間發(fā)送句柄的一點疑問5. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務器還是不能訪問?6. 實現(xiàn)bing搜索工具urlAPI提交7. 配置Apache時,添加對PHP的支持時語法錯誤8. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化9. javascript - 移動端上不能實現(xiàn)拖拽布局嗎?10. phpstudy8.1支持win11系統(tǒng)嗎?

網(wǎng)公網(wǎng)安備