Lev
Lev

Reputation: 15674

unsubscribe from observable when it emits a certain value

How can I unsubscribe from an observable when I receive a certain value ?

Like this :

 let tempSub: Subscription = this.observable$.subscribe(value => {
    if (value === 'somethingSpecific') {
      tempSub.unsubscribe(); 
      // doesn't work 
      //because when this is reached tempsub is undefined
    }
  });

Upvotes: 0

Views: 402

Answers (1)

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

You can use the takeWhile operator

source.takeWhile(val => val === 'somethingSpecific');

or

this.observable$
.takeWhile(val => val === 'somethingSpecific')
.subscribe(value => {
 // .. do something
});

don't forget to import it

here is an example https://jsfiddle.net/btroncone/yakd4jgc/

Upvotes: 5

Related Questions