【问题标题】:Unsubscribe in a condition does not allow to subscribe in Angular RXJS取消订阅条件不允许在 Angular RXJS 中订阅
【发布时间】:2021-03-03 22:57:33
【问题描述】:

我有一项显示穿着、信息和错误通知的服务。 有时通知来得很频繁。让我们说 20-30 在同一时间,我试图通过在特定时间间隔发生时取消订阅来避免这件事。

退订后就不能再订阅了。

  const locationsSubscription = this.messageService
      .getMessage()
      .pipe(timeInterval(), tap(console.log))
      .subscribe(message => {    
        if (message.interval < 500) {          
          locationsSubscription.unsubscribe();
        }
        else {
             switch (message.type){       
            case MessageType.Info:
              this.showInfo(message.text);
              break;
            case MessageType.Warning:
              this.showWarning(message..text);
              break;
            case MessageType.Error:
              this.showError(message.value);
              break;
          }
        }
      });

【问题讨论】:

  • 为什么要退订?
  • 因为有很多通知,不想全部显示

标签: angular rxjs subscription unsubscribe


【解决方案1】:

只需使用debounceTimethrottleTime 在经过一段时间后触发警告:

this.messageService
      .getMessage()
      .pipe(
         debounceTime(500) // to allow messages to trigger after 500ms of inactivity (idle)
         // throttleTime(500) // to allow only one message per 500ms (first or last)
      )

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2018-07-29
    • 2021-12-19
    • 2017-03-26
    • 2020-10-28
    相关资源
    最近更新 更多