【问题标题】:invoke subscribe on 2nd observable based on the value of the first根据第一个的值在第二个 observable 上调用订阅
【发布时间】:2019-09-09 19:06:33
【问题描述】:

我需要进行 2 个 API 调用,第一个将始终执行并返回 true 或 false。如果第一个返回 true,第二个应该只调用订阅。

有没有我可以使用的 Rxjs 操作符,而不是在订阅中加入订阅?

我在调用 2 个订阅时使用了 switchmap,但在那种情况下,我将结果从第一个传递到第二个,而第二个总是必须执行。

如果没有必要,我想避免第二次调用。

【问题讨论】:

    标签: angular rxjs rxjs5


    【解决方案1】:

    参考这篇文章。

    https://medium.com/javascript-everyday/rxjs-iif-operator-ternary-operator-under-the-hood-148b28e752e4

    https://rxjs-dev.firebaseapp.com/api/index/function/iif

    RXJS "IFF" 运算符提供了一种三元运算符的行为。

    firstCall(args).pipe(
       iif(res => res===true,secondCall(otherArgs),EMPTY),
    ).subscribe(doStuff);
    

    【讨论】:

      【解决方案2】:

      IMK 没有这样的 rxjs 运算符,这更多的是自定义应用程序需要,您必须为此编写自己的逻辑。通过管道传递 observable 而不是多次订阅来执行此逻辑。

      firstApiCall('url').pipe(
         mergeMap((data) => {  // your flattening operator
            if (data) {
              return secondApiCall('url')
            }
            return of(data)
         }
      )).subscribe((data) => {
           console.log(data)
      });
      

      【讨论】:

        【解决方案3】:

        filter 放在switchMap 之前。

        firstCall(args).pipe(
           filter(res => res === true),
           switchMap(() => secondCall(otherArgs),
        ).subscribe(doStuff);
        

        【讨论】:

        • IMK,添加过滤器不会让控件去订阅(在虚假条件下),因为我们正在过滤流。
        猜你喜欢
        • 1970-01-01
        • 2019-01-26
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 2019-01-21
        • 1970-01-01
        相关资源
        最近更新 更多