【问题标题】:RxJS Emitting Subscribe TwiceRxJS 发射两次订阅
【发布时间】:2018-09-05 06:12:13
【问题描述】:

我有一个 RXJS 函数,它将创建一个空的 Observable,点击结果并返回那个新的 observable。我希望 observable 始终运行 tap 所以我 noop 订阅(在实际情况下它可能永远不会被订阅)。

function that() {
  let obs = of({});
  obs = obs.pipe(tap(() => console.log('here')))
  obs.subscribe();
  return obs;
}

const res = that();
res.subscribe(() => console.log('finished'))

如果您在StackBlitz 上运行此代码,您会注意到here 被触发了两次。输出如下所示:

 here
 here
 finished

我尝试了几种不同的方法,但我似乎永远无法让它在不发射两次的地方工作。

【问题讨论】:

    标签: rxjs


    【解决方案1】:

    是否只是只点击内订阅的情况?

    function that() {
      let obs = of({});
      obs.pipe(tap(() => console.log('here'))).subscribe();
      return obs;
    }
    
    const res = that();
    res.subscribe(() => console.log('finished'))
    

    【讨论】:

      【解决方案2】:

      您订阅了两次:

      function that() {
          let obs = of({});
          obs = obs.pipe(tap(() => console.log('here')))
          obs.subscribe(); // first subscription
          return obs;
      }
      
      const res = that();
      res.subscribe(() => console.log('finished')) // second subscription
      

      这与您订阅的 observable 相同,一次是在函数中,然后是返回值。

      只是不要订阅函数

      function that() {
          let obs = of({});
          obs = obs.pipe(tap(() => console.log('here')))
          return obs;
      }
      
      const res = that();
      res.subscribe(() => console.log('finished')) // subscribe from here only
      

      查看更新后的StackBlitz

      【讨论】:

      • 是的,我想那么多。我怎样才能让它不那样做并且仍然订阅两次?
      • 这是一个非常简化的案例,在实际案例中,我必须 noop subscribe 以确保 tap 始终运行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      相关资源
      最近更新 更多