我尝试重复请求,直到响应有使用RxJS的数据,此时我想调用成功(或失败)处理程序,但我遇到了麻烦w / RxJS。这是我目前的做法:
// ... redux-observable action observable
.mergeMap(() =>
fetchData()
.repeatWhen(response =>
response.takeWhile(({ data }) => !data.length)
.of(response)
)
)
.map(successFunction)
.catch(failureFunction);
免责声明:我对RxJS很新......
答案 0 :(得分:4)
听起来你想要抑制ajax结果并重试,直到你得到你想要的响应。我是这样做的:
// observable that will re-fetch each time it is subscribed
const request = Observable.defer(() => fetchData());
// each time request produces its value, check the value
// and if it is not what you want, return the request
// observable, else return an observable with the response
// use switchMap() to then subscribe to the returned
// observable.
const requestWithRetry = request.switchMap(r =>
r.data.length ? Observable.of(r) : requestWithRetry);
答案 1 :(得分:3)
空数据不是错误,所以首先我们检查数据是否为空,如果是,则抛出错误。
然后retryWhen
可用于测试此错误,并在其发生时重试。
.mergeMap(() =>
fetchData()
.map(data => {
if (!data.length) {
throw 'no data';
}
return data;
})
.retryWhen(errors => errors.takeWhile(error => error === 'no data'))
)
.map(successFunction)
.catch(failureFunction);
答案 2 :(得分:3)
在一个间隔上重复请求,过滤其结果并采取一次发射更简单。
Observable.timer(0, 500)
.flatMap(() => fetchData())
.filter(r => r.data && r.data.length)
.take(1)
.timeout(10000)