【问题标题】:RxJS takeUntil doesn't unsubscribeRxJS takeUntil 不会取消订阅
【发布时间】:2019-03-11 22:15:27
【问题描述】:

我想使用“takeUntil”运算符以声明式方式取消订阅。但这基本上是行不通的。反正我可以看到控制台输出。

const unsubscribe = new Subject();

function printFoo() {
  of('foo')
    .pipe(takeUntil(unsubscribe))
    .subscribe(console.log) // Why I can see 'foo' in the  console?
}

function onDestroy() {
  unsubscribe.next();
  unsubscribe.complete();
}

onDestroy()
setTimeout(() => printFoo(), 200)

斯塔克闪电战:

https://stackblitz.com/edit/rxjs-svfkxg?file=index.ts

P.S.我预计即使unsubscribe.next() 也足以取消订阅,但即使使用unsubscribe.complete() 也不起作用。

【问题讨论】:

    标签: javascript rxjs reactive-programming


    【解决方案1】:

    在带有takeUntil 的链甚至创建之前,您就调用了onDestroy()。

    当您最终调用 printFoo() 时,之前对 unsubscribe 的发射不会被重新发射,而且主题 unsubscribe 已经完成,因此在这种情况下 takeUntil 将永远不会完成链。

    【讨论】:

      【解决方案2】:

      因为主题在printFoo 订阅之前发出。

      订阅后,不再有 Subject 发射。

      您可以改用 BehaviorSubject,因为它包含发出的值(最后一个 发射值):

      const unsubscribe = new BehaviorSubject(false);

      function printFoo() {
        of('foo')
          .pipe(takeUntil(unsubscribe.pipe(filter(value => !!value)))) // Don't unsub if it's false emitted
          .subscribe(console.log)
      }
      
      function onDestroy() {
        unsubscribe2.next(true); // Emit true to cancel subscription
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 2018-11-09
        • 2017-04-10
        • 2018-11-05
        • 1970-01-01
        • 2018-08-20
        • 2017-03-26
        • 2020-10-28
        • 2021-11-18
        相关资源
        最近更新 更多