根据第一个值调用第二个可观察值的订阅

invoke subscribe on 2nd observable based on the value of the first

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

有没有我可以使用的 Rxjs 运算符,而不是将订阅放在订阅中?

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

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

filter 放在 switchMap 之前。

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

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

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

参考这篇文章。

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