Piotr Stapp
Piotr Stapp

Reputation: 19830

RxJS queue http request

I'm trying to implement save in a sequence in Angular. So the "save" request should wait until the previous one ends. I have to wait because the previous call returns an ETag.

I was thinking about some "map" in RxJS but I don't know how to wait until the previous one ends.

The main idea is shown in: https://stackblitz.com/edit/typescript-mmcqhy?file=index.ts

Upvotes: 1

Views: 3957

Answers (3)

tszczerba
tszczerba

Reputation: 21

Here is solution with mergeMap concurency - https://stackblitz.com/edit/typescript-y4nu3i?file=index.ts

callQueue$
.pipe(
    mergeMap(result => save(result), 1)
    )
  .subscribe(
    function (data) {
      console.log("finished OK request")
    }
  );

Upvotes: 2

martin
martin

Reputation: 96889

One way could be using concatMap and then tap for the inner logs but it really depends on what behavior you expect.

let save = function(arg){
  console.log("start request")
  return ajax('https://httpbin.org/get').pipe(
    tap(...),
  );
}

callQueue$.pipe(
  concatMap(i => save(i)),
)
.subscribe(result => {
  ...
});

Your updated demo: https://stackblitz.com/edit/typescript-13jrrk?file=index.ts

Upvotes: 1

rtn
rtn

Reputation: 2034

I done it the following with concat:

import { concat } from 'rxjs/observable/concat';

const source = concat(
    this.myService.saveStuff({ test: 'swag' }), //returns an observable
    this.myService.saveStuff({ test: 'yolo' })
);

source.subscribe(
    response => {
        console.log('Called after each successful save');
    },
    () => {
        console.log('Called when an error happens')
    },
    () => {
        console.log('called when all observables are complete')
    });

Upvotes: 0

Related Questions