服務器的輪詢操做
- 好比向服務器獲取短信驗證碼
public void getMsgCodeWithRetry(String token ,String projectId,String phone) { EmaMsgModel emaMsgModel = new EmaMsgModel(); Observable.interval(5,TimeUnit.SECONDS) .take(11) .flatMap(new Func1<Long, Observable<String>>() { @Override public Observable<String> call(Long aLong) { Log.v(TAG,"flatMap:" + String.valueOf(aLong)); if(aLong == 10) { throw new RuntimeException("獲取驗證碼超過十次了"); } return emaMsgModel.getMsgCode_EMA(token,projectId,phone); } }) .takeUntil(new Func1<String, Boolean>() { @Override public Boolean call(String s) { Log.v(TAG,"takeUntil:" + s); return !s.contains("False"); } }) .filter(new Func1<String, Boolean>() { @Override public Boolean call(String s) { Log.v(TAG,"filter:" + s); return !s.contains("False"); } }) .subscribe(new Action1<String>() { @Override public void call(String s) { Log.v(TAG,"Action1:" + s); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Log.v(TAG,throwable.getMessage()); throwable.printStackTrace(); } }, new Action0() { @Override public void call() { Log.v(TAG,"onComplete"); } }); }
執行結果
12-06 05:54:59.936 21790-21892/com.lt.accesstask V/MainActivity: flatMap:0java
12-06 05:55:00.176 21790-21892/com.lt.accesstask V/MainActivity: filter:False:沒有短信,請5秒後再試服務器
12-06 05:55:00.176 21790-21892/com.lt.accesstask V/MainActivity: takeUntil:False:沒有短信,請5秒後再試ide
12-06 05:55:04.934 21790-21892/com.lt.accesstask V/MainActivity: flatMap:1code
12-06 05:55:05.288 21790-21892/com.lt.accesstask V/MainActivity: filter:False:沒有短信,請5秒後再試token
12-06 05:55:05.288 21790-21892/com.lt.accesstask V/MainActivity: takeUntil:False:沒有短信,請5秒後再試get
......it
12-06 05:55:44.935 21790-21892/com.lt.accesstask V/MainActivity: flatMap:9io
12-06 05:55:45.118 21790-21892/com.lt.accesstask V/MainActivity: filter:False:沒有短信,請5秒後再試驗證碼
12-06 05:55:45.118 21790-21892/com.lt.accesstask V/MainActivity: takeUntil:False:沒有短信,請5秒後再試class
12-06 05:55:49.937 21790-21892/com.lt.accesstask V/MainActivity: flatMap:10
12-06 05:55:49.948 21790-21892/com.lt.accesstask V/MainActivity: 獲取驗證碼超過十次了
12-06 05:55:49.950 21790-21892/com.lt.accesstask W/System.err: at com.lt.accesstask.MainActivity$1.call(MainActivity.java:107)
12-06 05:55:49.951 21790-21892/com.lt.accesstask W/System.err: at com.lt.accesstask.MainActivity$1.call(MainActivity.java:102)
打印一組數據,能夠指定間隔時間
能夠將該數據打包在一個數據中,用interval和take操做符進行打印。
批量下載多個任務
- 好比同時下載七八個文件,下載完成以後MD5檢驗,轉存