【问题标题】:How to avoid nested rxJS subscription如何避免嵌套的 rxJS 订阅
【发布时间】:2019-10-03 23:08:32
【问题描述】:

我开始了一个新的 Angular 7 项目,我需要在其中调用 API 来获取结果列表。然后,如果特定结果在列表中,我选择它,如果没有,我创建它调用另一个 API 端点。所有这些东西都应该在ngOnInit() 方法中完成。

为了简化问题,我有以下代码:

const subject = new BehaviorSubject(null);
subject.next(6);

const res$ = subject.pipe(
  mergeMap(() => getValues()),
  tap((res) => {
    const exists = res.find(x => subject.value === x) || null;
    if (exists === null) {
      // TODO: call the getNew() function, but I don't want nested call
    } else {
      // Do nothing
    }
  })
);

// res$ should contains [1, 2, 3, 4, 5, 6]
res$.subscribe(x => console.log(x));

function getValues() {
  // Mocking the API call
  return of([1, 2, 3, 4, 5]);
}

function getNew() {
  // Mocking the API call
  return of(6);
}

最后,res$ observable 应该包含所有数组(带有附加值),我想避免嵌套订阅。

非常感谢!

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

    两件事:

    1. 不要指望可以访问主题的值。相反,您可以使用mergeMap 的替代形式,它允许您从源和新流中创建选择值。在这种情况下,我使用它在流中返回一个新项目,其中包含来自内部 observable 的源和值。

    2. 您可以使用另一个 mergeMap 来返回原始结果或新 api 调用的结果,方法是将原始结果包装在 of 中以创建新的内部 observable。

      李>
    const res$ = subject.pipe(
      mergeMap(x => getValues(), (orig, res) => ({ orig, res })),
      mergeMap(({ orig, res }) => {
        const exists = res.find(x => x === orig) || null;
        return (exists) 
          ? of(res)
          : getNew().pipe(map(x => [... res, x]))
      })
    );
    

    Stackblitz

    【讨论】:

    • 谢谢,它正在工作!请注意,mergeMap 不再支持 resultSelector,最好使用内部映射。使用mergeMap(orig => getValues().pipe(map(res => ({orig, res})))), 而不是mergeMap(x => getValues(), (orig, res) => ({ orig, res })),
    • @youri - 疯了!我经常使用 resultSelector。我觉得它会产生更干净、平坦的溪流。哦,好的,谢谢你的信息。
    【解决方案2】:

    解决此问题的一种方法是将其拆分为两个可观察对象,然后将它们再次与 combineLatest 组合。我们将使用 resFirst$ observable 两次,并根据它是否为空来过滤它。

    import { combineLatest } from 'rxjs';
    
    ---
    
    const subject = new BehaviorSubject(null);
    subject.next(6);
    
    const resFirst$ = subject.pipe(
        mergeMap(() => getValues()),
        map((res) => res.find(x => subject.value === x) || null)
    );
    
    const resSecond$ = resFirst$.pipe(
        filter(exists => exists === null), <--- FILTERING FOR IS NULL
        mergeMap(() => getNew()) <--- SWITCHMAP COULD ALSO BE USED HERE DEPENDING ON WHAT YOU WANT
    );
    
    const final$ = combineLatest(resFirst$, resSecond$)
        .pipe(filter(exists => exists !== null)) <--- FILTERING FOR NOT NULL
        .subscribe(x => console.log(x));
    
    function getValues() {
        // Mocking the API call
        return of([1, 2, 3, 4, 5]);
    }
    
    function getNew() {
        // Mocking the API call
        return of(6);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 2023-01-11
      • 2020-08-18
      • 2022-06-22
      • 2023-01-30
      • 2019-08-20
      • 2018-11-27
      • 2022-08-25
      • 1970-01-01
      相关资源
      最近更新 更多