通常在Rxjava中我會用interval當(dāng)定時(shí)器與flatmap結(jié)合發(fā)起網(wǎng)絡(luò)請求.在項(xiàng)目中的實(shí)際需求是每兩個(gè)小時(shí)請求一次,這條異常就跳過,繼續(xù)請求下一條,但是發(fā)現(xiàn)一個(gè)問題就是請求可能會超時(shí)異常.為了舉例方便,現(xiàn)在我將代碼改為類似的可能返回異常的簡單替代
public static void main(String[] args) {
Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.trampoline())
.flatMap(new Function<Long, ObservableSource<Long>>() {
@Override
public ObservableSource<Long> apply(Long aLong) throws Exception {
return Observable.just(aLong == 3 ? aLong / 0 : aLong * 2);
}
})
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long integer) throws Exception {
System.out.println(integer + "");
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
System.out.println(throwable.toString());
}
});
}
我們的期望是出錯(cuò)調(diào)用錯(cuò)誤處理后interval繼續(xù)發(fā)射數(shù)據(jù),繼續(xù)請求下一個(gè),我們看一打印結(jié)果:
0
2
4
java.lang.ArithmeticException: / by zero
結(jié)果是顯而易見的,在異常出現(xiàn)且被處理后,interval停止了數(shù)據(jù)的發(fā)射,究其原因是在整個(gè)鏈路中flatMap返回了一個(gè)Observable<Throwable>導(dǎo)致鏈路中斷,讓interval繼續(xù)輪詢請求的關(guān)鍵便是flatMap返回異常時(shí)鏈路不能被中斷,但是實(shí)在找不到合適的操作符,于是干脆把flatMap的操作放在了訂閱者中,這樣interval就不會被flatMap返回的錯(cuò)誤結(jié)果打斷了!先貼代碼:
Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.trampoline())
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
Observable.just(aLong).
flatMap(new Function<Long, ObservableSource<Long>>() {
@Override
public ObservableSource<Long> apply(Long aLong) throws Exception {
return Observable.just(aLong == 3 ? aLong / 0 : aLong * 2);
}
})
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long integer) throws Exception {
System.out.println(integer + "");
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
System.out.println(throwable.toString());
}
});
}
});
打印結(jié)果:可以繼續(xù)下去了
0
2
4
java.lang.ArithmeticException: / by zero
8
10
12
但是這樣真的好不優(yōu)雅,求大神指教有什么優(yōu)雅的方法嗎?