[英]How do i repeat an ajax request until a condition is met with RxJS Observable?
I'm attempting to repeat a request until the response has data using RxJS, at which point I'd like to call a success (or failure) handler, but I'm having trouble w/RxJS. 我试图重复一个请求,直到响应有数据使用RxJS,此时我想调用一个成功(或失败)处理程序,但我遇到了RxJS的问题。 Here's my current approach:
这是我目前的做法:
// ... redux-observable action observable
.mergeMap(() =>
fetchData()
.repeatWhen(response =>
response.takeWhile(({ data }) => !data.length)
.of(response)
)
)
.map(successFunction)
.catch(failureFunction);
Disclaimer: I'm quite new to RxJS.... 免责声明:我对RxJS很新....
It sounds like you want to suppress ajax results and retry until you get the response you want. 听起来你想要抑制ajax结果并重试,直到你得到你想要的响应。 I'd do it like so:
我会这样做:
// 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);
Empty data is not an error so first we check if the data is empty and throw an error if it is. 空数据不是错误,所以首先我们检查数据是否为空,如果是,则抛出错误。 then
retryWhen
can be used to test for this error and retry as long as it's occurring. 然后重试当可以用来测试此错误
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);
It's simpler to repeat the request on an interval, filter on its result and take one emission. 在一个间隔上重复请求,过滤其结果并采取一次发射更简单。
Observable.timer(0, 500)
.flatMap(() => fetchData())
.filter(r => r.data && r.data.length)
.take(1)
.timeout(10000)
http://jsbin.com/cafericore/1/edit?js,console http://jsbin.com/cafericore/1/edit?js,console
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.