RxJS queue http request

时间:2019-01-07 13:10:23

标签: typescript rxjs

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

3 个答案:

答案 0 :(得分:2)

这是mergeMap并发性的解决方案-https://stackblitz.com/edit/typescript-y4nu3i?file=index.ts

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

答案 1 :(得分:1)

一种方法可能是先使用concatMap,然后再使用tap作为内部日志,但这实际上取决于您期望的行为。

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

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

您的更新演示:https://stackblitz.com/edit/typescript-13jrrk?file=index.ts

答案 2 :(得分:0)

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')
    });