如何在订阅方法中取消订阅 RXJS 订阅?

Moj*_*oMS 6 rxjs rxjs-observables

我有一些 javascript:

this.mySubscription = someObservable.subscribe((obs: any) => {
   this.mySubscription.unsubscribe();
   this.mySubscription = undefined;
}
Run Code Online (Sandbox Code Playgroud)

执行时,控制台会记录错误ERROR TypeError: Cannot read property 'unsubscribe' of undefined。我想知道为什么我不能在 subscribe lambda 函数中取消订阅。有正确的方法吗?我已经阅读了一些关于使用虚拟主题并完成它们或使用 takeUntil/takeWhile 和其他管道操作符 workArounds 的内容。

在订阅的订阅功能中取消订阅订阅的正确方法/解决方法是什么?

我目前正在使用一个虚拟订阅,如下所示:

mySubscription: BehaviorSubject<any> = new BehaviorSubject<any>(undefined);


// when I do the subscription:
dummySubscription: BehaviorSubject<any> = new BehaviourSubject<any>(this.mySubscription.getValue());
this.mySubscription = someObservable.subscribe((obs: any) => {
    // any work...
    dummySubscription.next(obs);
    dummySubscription.complete();
    dummySubscription = undefined;
}, error => {
    dummySubscription.error(error);
});

dummySubscription.subscribe((obs: any) => {
    // here the actual work to do when mySubscription  emits a value, before it should have been unsubscribed upon
}, err => {
    // if errors need be
});
Run Code Online (Sandbox Code Playgroud)

fri*_*doo 8

您不应该尝试取消订阅该subscribe功能。
您可以使用taketakeWhile或等运营商取消订阅takeUntil

用于take(n)someObservable发出n次数后取消订阅。

someObservable.pipe(
  take(1)
).subscribe(value => console.log(value));
Run Code Online (Sandbox Code Playgroud)

边走边看

用于takeWhile在发出的值未能满足条件时取消订阅。

someObservable.pipe(
  takeWhile(value => valueIsSave(value))
).subscribe(value => console.log(value));

valueIsSave(value): boolean {
  // return true if the subscription should continue
  // return false if you want to unsubscribe on that value
}
Run Code Online (Sandbox Code Playgroud)

直到

用于takeUntil(obs$)在 observableobs$发出时取消订阅。

const terminate = new Subject();

someObservable.pipe(
  takeUntil(terminate)
).subscribe(value => console.log(value));

unsub() { 
  terminate.next() // trigger unsubscribe
}
Run Code Online (Sandbox Code Playgroud)

  • @MojioMS 听起来“takeWhile”应该适合你 (2认同)