[英]How to continue polling with observable interval if error occurs
I have a simple network polling function with observable intervals我有一个简单的网络轮询 function 具有可观察的间隔
private fun pollFromApi(): Observable<MyState> {
return Observable.interval(3L, TimeUnit.SECONDS, schedulerProvider.io())
.startWith(0L)
.flatMap {
api.getState().toObservable()
}
.map {
// map response to MyState
}
.onErrorReturn {
return@onErrorReturn MyState.Polling // if error occurred emit Polling State
}
.takeUntil {
// stop polling if certain State is reached
}
}
The problem I have is that if in the middle of polling one of the network API calls fails, the polling stops.我遇到的问题是,如果在轮询其中一个网络 API 调用失败时,轮询将停止。 Ideally what I want is to keep retrying until
takeUntil
stops the polling and if an error occurs, just ignore it and do not emit anything to observers.理想情况下,我想要的是继续重试,直到
takeUntil
停止轮询,如果发生错误,只需忽略它并且不向观察者发出任何内容。
I tried adding onErrorReturn
but that just catches the error and stops the polling.我尝试添加
onErrorReturn
但这只是捕获错误并停止轮询。
You can use Observable#onErrorResumeNext
operator chained to your remote (possibly failing) API call, emitting an item that does not meet your #takeUntil
clause to avoid stopping processing:您可以使用
Observable#onErrorResumeNext
运算符链接到远程(可能失败)API 调用,发出不符合您的#takeUntil
子句的项目以避免停止处理:
private fun pollFromApi(): Observable<MyState> {
return Observable.interval(3L, TimeUnit.SECONDS, schedulerProvider.io())
.startWith(0L)
.flatMap {
api.getState().toObservable().onErrorResumeNext(ignored -> null) // or some other SENTINEL value
}
.map {
// map response to MyState
}
.takeUntil {
// stop polling if certain State is reached
}
}
As I mentioned in the comments, you'll have to do the mapping and error handling on the api call itself inside the flatMap
:正如我在评论中提到的,您必须在
flatMap
中对 api 调用自身进行映射和错误处理:
private fun pollFromApi(): Observable<MyState> {
return Observable.interval(3L, TimeUnit.SECONDS, schedulerProvider.io())
.startWith(0L)
.flatMap {
api.getState().toObservable()
.map {
// map response to MyState
}
.onErrorReturn {
return@onErrorReturn MyState.Polling // if error occurred emit Polling State
}
}
.takeUntil {
// stop polling if certain State is reached
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.