How do I repeat the ajax request until the condition is satisfied using the RxJS Observable?

I try to retry the request until the response has data using RxJS, at which point I would call a successful (or unsuccessful) handler, but I have problems with RxJS. Here is 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 completely new to RxJS ....

+4
source share
3 answers

It looks like you want to suppress ajax results and try again until you get the answer you want. I would do it like this:

// 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);
+4
source

, , , . 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);
+3

It’s easier to repeat the request on the interval, filter its result and accept one issue.

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

0
source

Source: https://habr.com/ru/post/1674785/


All Articles