首页 > 解决方案 > RxJS 有条件地订阅嵌套的 observable

问题描述

下面的场景是否有 RxJS 运算符?

obs1.pipe(
   // if (condition is met based on the result of obs1)
   // subscribe to another observable [obs2] (retrieve data from server which will be used elsewhere)
).subscribe(value => {
   // return value of obs1
   // result of obs2 not needed here
});

标签: rxjs

解决方案


你可以试试这样的

obs1.pipe(
   concatMap(res_1 => 
      // concatMap return an Observable. Depending on the condition, the Observable
      // returned may contain just res_1 or res_1 and something from res_2
      res_1 === "whatever_condition" ? 
         of(res_1) :
         obs2.pipe(
           map(res_2 => {
              // do something with res_2
              // and then return somehow both res_1 and res_2 or just res_1 if
              // res_2 is not used are returned value
              return {res_1, res_2}
           })
         )
   )
).subscribe(value => {
   // here you either receive res_1 or an object {res_1, res_2}
   // depending on the value of the condition retrieve by obs1
});

推荐阅读