简体   繁体   中英

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM