Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay next(value) on subject?

Tags:

My AlertService has private subject = new Subject<Alert>();. I want to autocratically clear alert after 5 seconds. I can do it with using setTimeout() like this:

autoClear(alertId?: string) {
   setTimeout(
      () => this.subject.next(new Alert({alertId})),
   5000);
  }

I tried to do that more elegant and I created this code:

autoClear(alertId?: string) {
    const delay = new Observable(x => {
      x.next();
    }).delay(5000).subscribe(() => {
      this.subject.next(new Alert({alertId}));
      delay.unsubscribe();
    });
  }

Both of example works but it doesn't look like a proper way of using RxJS. How can I improve it?