使用条件rxjs6重构嵌套订阅

时间:2018-12-18 06:25:10

标签: typescript rxjs angular7

我知道不建议使用嵌套订阅,但是在重构它们时找不到任何好的资源。

这是我目前的代码:

this.checkExists(request.id).subscribe(exists => {
  if (exists) {
    this.getDeleteReason(request.id).subscribe(reason => {
      if (reason) {
        this.checkExists(request.id).subscribe(exists2 => {
          if (exists2) {
            // DO DELETE
          }
        });
      }
    });
  }
});

我曾尝试过使用mergeMap,但总是被束缚。

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:2)

filtermergeMap / switchMap的组合。

 this.checkExists(request.id).pipe(
    filter(exists => exists),
    mergeMap(() => this.getDeleteReason(request.id)),
    filter(reason => reason),
    mergeMap(() => this.checkExists(request.id)),
    filter(exist2 => exist2)
  }).subscribe(() => {
      //do delete
  });

编辑: 有几种方法可以将reason传递给订阅。在这种情况下,我要在reason旁边添加exist2

this.checkExists(request.id).pipe(
    filter(exists => exists),
    mergeMap(() => this.getDeleteReason(request.id)),
    filter(reason => reason),
    mergeMap(reason => ({
             exist2: this.checkExists(request.id), 
             reason})),
    filter(({exist2}) => exist2)
  }).subscribe(({reason}) => {
      //do delete
  });

答案 1 :(得分:0)

如果它们是三个单独的任务/可观察对象,则考虑使用forkJoin

let observable1(param1);
let observable2(param2);
let observable3(param3);

let joinedObservables = forkJoin(observable1, observable2, observable3).subscribe(x => {
  let result1 = x[0];
  let result2 = x[1];
  let result3 = x[2];

  ...
});

如果它们的结果相互依赖,则可以使用switchMapflatMapmergeMapexhaustMap(检查差异)

let resultObservable =  return this.observable1().pipe(mergeMap((param1) => {
  return this.observable2().pipe(map((param1) => {

    ....        

    return <result>;
  }));
}));

resultObservable.subscribe(x => {
   ...
});