使用Rxjava2+ Retrofit 进行网络请求,在请求失败之后,使用retryWhen实现重新请求(如下面代码)。但发现没有实现预想的功能:
class TestRetryWhenHeartBeatException : Function<Observable<out Throwable>, ObservableSource<*>> {
companion object {
private val DELAY: Long = 6
private val TAG:String = TestRetryWhenHeartBeatException::class.java.simpleName
}
override fun apply(t: Observable<out Throwable>): ObservableSource<*> {
logd(TAG,"retry when")
return t.flatMap { Observable.timer(DELAY, TimeUnit.SECONDS) }
}
}
mHeartBeatDisposable =
Observable.interval(5,TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
// .repeatWhen(RepeatWhenHeartBeatCompleted())
.retryWhen(TestRetryWhenHeartBeatException())
.flatMap {
if (TaskManager.mIdle) {
logd(TAG, "heartbeat")
mNetWorkApi.heartBeat(UrlManager.HEARTBEAT_URL)
} else {
Observable.create { emitter ->
//emit a HttpResult with no data
emitter.onNext(nullHeartBeat)
}
}
}
.subscribe({ data ->
RxBus.getDefault().post(LostServerEvent(false))
logd(TAG, "post lost server false")
}, { e ->
loge(TAG, e.message)
loge(TAG, "lost server")
RxBus.getDefault().post(LostServerEvent(true))
}, {})