Search code examples
angularrxjssubscriptionunsubscribe

Unsubscribe in a condition does not allow to subscribe in Angular RXJS


Im having a service that show wornings,info, and error notifications. Sometimes the notifications come very often. Lets say 20-30 in same time and im trying to avoid this thing by unsubscribing when a specifiv time interval happens.

After unsubscribe than its not anymore possibile to subscribe.

  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;
          }
        }
      });


Solution

  • Just use debounceTime or throttleTime to trigger warnings after some time is passed:

    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)
          )