【问题标题】:How to unsubscribe immediately after the the condition is met in RxJs如何在 RxJs 中满足条件后立即取消订阅
【发布时间】:2018-12-14 06:12:45
【问题描述】:

我是 RxJs 可观察对象的新手,一旦满足条件,我发现取消订阅循环有困难,请你帮帮我

在下面的函数中,如果代码到达我想取消订阅 Observables 的 if 块

在问这个问题之前,我已经解决了以下问题,但没有一个对我有太大帮助

  1. Rxjs observable wait until some condition is met
  2. AngularJs - RXJS Observable unsubscribe

Javascript 函数

this.router.events.subscribe((url: any) => {
    url = this.router.url;
    if ((url === "/profile" || url === "/summary") && this.filterConfigFlag === false) {

        /*
        Perform operations
        */

    } else {
        console.log(typeof (url), url);

    }
});

【问题讨论】:

  • 所以你想运行 next 处理程序并在此之后立即完成 Observable?
  • @martin 是的,如果匹配的话我想继续
  • “继续”是什么意思。继续接收更多物品还是完成?
  • @martin 我想完成它。

标签: javascript angular rxjs observable


【解决方案1】:

你可能想要takeWhile:

this.router.events
  .pipe(
    takeWhile(url => url === ...), // when the condition isn't met it'll complete immediately
  )
  .subscribe(...);

但如果您还想包含最后一个值(完成 Observable 的值),您需要执行以下操作:

在 RxJS 6.4 之前

this.router.events
  .pipe(
    concatMap(url => url === ... ? of(url, null) : of(url)),
    takeWhile(Boolean),
  )
  .subscribe(...);

从 RxJS 6.4 开始

RxJS 6.4 为 takeWhile 添加了重载,现在可以像这样包含最后一个值:

this.router.events
  .pipe(
    takeWhile(url => url === ..., true),
  )
  .subscribe(...);

【讨论】:

【解决方案2】:

您可以使用SubjecttakeUntil 运算符,如下所示:

unsubscribe = new Subject<any>();

this.router.events.pipe(takeUntil(unsubscribe)).subscribe((url: any) => {
    url = this.router.url;
    if ((url === "/profile" || url === "/summary") && this.filterConfigFlag === false) {

        /*
        Perform operations
        */
this.unsubscribe.next();
    } else {
        console.log(typeof (url), url);
this.unsubscribe.next();
    }
});

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 2016-09-25
    • 2021-03-03
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    相关资源
    最近更新 更多