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. 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....
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
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.
.mergeMap(() =>
fetchData()
.map(data => {
if (!data.length) {
throw 'no data';
}
return data;
})
.retryWhen(errors => errors.takeWhile(error => error === 'no data'))
)
.map(successFunction)
.catch(failureFunction);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With