Home > Back-end >  How do I use RxJS to post transactions such that the next request waits for the previous one complet
How do I use RxJS to post transactions such that the next request waits for the previous one complet

Time:04-12

I have a list of about 2000 transactions to post to a back-end. I want to make a request to POST the first transaction, wait for that request to complete, then move the next and so on, until I have exhausted the whole list.

CodePudding user response:

A simple map will do it:

const trans = [...];

//convert static array of values into a observable
const $trans = from(trans);
const $submitted = $trans.pipe(
  map(m => {
    //transform the list of values
    return submitFunc(m);
  })
);

//note each call to submitFunc will trigger next in the below
$submitted.subscribe();

Presuming the async submitFunc returns a compatible observable.

CodePudding user response:

you need to use concatMap or exhaustMap

concatMap - will call first API and will proceed to the next API only if first API call will be completed

All calls in concatMap called strictly in order

const { from, of } = require("rxjs");
const { concatMap } = require("rxjs/operators");

const transId = ["id1", "id2", "id3"];

const postAPI = (id) => of({ id, status: "success" });

from(transId)
  .pipe(concatMap((id) => postAPI(id)))
  .subscribe(console.log);

  • Related