prathameshk73
prathameshk73

Reputation: 1088

Multiple sequential AJAX requests RXJS

I am trying to make multiple AJAX request sequentially with some delay in each request. I would expect sequential response from each request. I have tried mergeMap rxjs operator. It works well but I want the response with some delay. Currently I am getting the response for each request sequentially but I need some delay in each response.

import { of, from, interval } from 'rxjs'; 
import { map, mergeMap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

const items = [1,2,3,4,5];

const requests = from(items)
    .pipe(
      mergeMap(item => ajax.getJSON(`https://api.github.com/users/${item}`)),  
);
 requests.subscribe(
      data => console.log(data), //process item or push it to array 
      err => console.log(err)
);

Here is the stackbliz example.

Multiple AJAX request RXJS

Upvotes: 2

Views: 828

Answers (3)

grzim
grzim

Reputation: 604

from(items)

will create a 'cold observable' what means the entire array will proceed immediately. If you want to add a delay before sending a request (not to send requests at once) try using zip and an interval

import { interval, zip } from 'rxjs';
import { flatMap } from 'rxjs/operators';
const interval$ = interval(1000);
const requests$ = zip(from(items), interval$)
  .pipe(
    flatMap(([itmes]) => items),
    mergeMap(item => ajax.getJSON(`https://api.github.com/users/${item}`))
)

Upvotes: 0

reymon359
reymon359

Reputation: 1330

Try this code with delay:)

const items = [1,2,3,4,5];

const requests = from(items)
    .pipe(
        mergeMap(item => ajax.getJSON(`https://api.github.com/users/${item}`)),
        // delay each element by 1 sec
        concatMap(x => of(x).pipe(delay(1000)))
      );

 requests.subscribe(
      data => console.log(data), //process item or push it to array 
      err => console.log(err)
);

Similar case here:

Delay for every element with RXJS

More info about delay:

https://www.learnrxjs.io/learn-rxjs/operators/utility/delay

Upvotes: 0

wentjun
wentjun

Reputation: 42526

This can be done by utilising the delay operator.

But first, you will need to use concatMap on each element on the items observable array, such that a new observable with the delay time is created for every item on the items array.

const items = [1,2,3,4,5];

const requests = from(items)
    .pipe(
      concatMap(item => ajax.getJSON(`https://api.github.com/users/${item}`)
        .pipe(
           delay(1000),
        )
    ),  
);
 requests.subscribe(
      data => console.log(data), //process item or push it to array 
      err => console.log(err)
);

I have forked a new demo over here.

Upvotes: 3

Related Questions