Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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....

like image 458
seitzej Avatar asked Apr 13 '17 19:04

seitzej


2 Answers

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

like image 115
teebot Avatar answered Sep 30 '22 08:09

teebot


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);
like image 45
Ofer Herman Avatar answered Sep 30 '22 10:09

Ofer Herman