【问题标题】:Subscribe to observables in order and do actions in between按顺序订阅 observables 并在其间执行操作
【发布时间】:2021-01-21 04:42:53
【问题描述】:

我尝试使用 rxjs 运算符 concat 以正确的顺序订阅 3 个相互依赖的 observable。在第一个和第二个 observable 之间以及在最后一个 observable 之后必须执行一些操作。最大的问题:第一个的结果必须传递给第二个。我已经尝试了几件事。例如:

let foo = {};
concat(
  observable1().pipe(map(result => foo.id = result)),
  observable2(foo),
  observable3().pipe(map(() => console.log('ready')))
).subscribe();

没有像预期的那样工作。 observables 将按正确的顺序订阅,但第一个订阅的结果不会传递给第二个。 Angular 版本是 8。

【问题讨论】:

    标签: angular rxjs observable concatenation subscribe


    【解决方案1】:

    您正在寻找concatMap

    在这个例子中,我不确定它是否是正确的输出,提供更多细节

    import { of, concat } from "rxjs";
    import { concatMap, map } from "rxjs/operators";
    
    let foo = {};
    obs1(1)
      .pipe(
         map(result => {
          foo["id"] = result;
    
          return foo || result
        }),
        concatMap(resultOfFirst => obs2(resultOfFirst)),
        concatMap(resultOfSecond => obs3())
      )
      .subscribe(console.log);
    function obs1(simpleData) {
      return of(simpleData);
    }
    
    function obs2(simpleData) {
      return of(simpleData);
    }
    
    function obs3() {
      return of("ready");
    }
    

    演示:https://stackblitz.com/edit/typescript-uqhyei?file=index.ts&devtoolsheight=100

    【讨论】:

    • 我要补充一点,在这种情况下,switchMapmergeMapconcatMap 具有相同的最终行为,因为每个 observable 发出一次然后完成。
    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多