Home > Mobile >  Unsubscribe from a observable when condition is true in angular
Unsubscribe from a observable when condition is true in angular

Time:12-22

I'm trying close a popup after 5 seconds when it is loaded but the subscription finish before so i want to unsubscribe when the variable loaded is true

    this.closed = false;
    this.loaded$.subscribe(loaded => {
      if (loaded) {
        setTimeout(() => {
          this.modalService.dismissActiveModal();
        }, 5000);
      }
    }).unsubscribe();
  } 

CodePudding user response:

this.closed = false;
// define the subscription
const subscription: Subscription = this.loaded$.subscribe(loaded => {
  if (loaded) {
    setTimeout(() => {
      this.modalService.dismissActiveModal();
      subscription.unsubscribe(); // unsubscribe here
    }, 5000);
  }
});

How about this?

CodePudding user response:

this.closed = false;
this.loaded$
.pipe(
  filter(loaded => loaded),
  switchMap(_ => interval(5000)),
  take(1),
  tap(_ => this.modalService.dismissActiveModal())
)
.subscribe();
  • Related