当 observable 发出特定值时取消订阅

Lev*_*Lev 0 javascript reactive-programming rxjs typescript

当我收到某个值时,如何取消订阅可观察值?

像这样 :

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

Yor*_*lov 5

您可以使用takeWhile运营商

source.takeWhile(val => val === 'somethingSpecific');
Run Code Online (Sandbox Code Playgroud)

或者

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

不要忘记导入它

这是一个示例https://jsfiddle.net/btroncone/yakd4jgc/