首页 文章

在继续使用Observables中的下一个之前,你如何取消或取消订阅?

提问于
浏览
0

我对Rxjs / Observables很新,它真的开始打扰我了 . 我已经使用Observable来检查方法,并确保在每个方法完成后逐个调用它们(使用next()函数) . 那么,如果可以说所有5个下一次调用中的第二个调用某些数据有问题,你如何取消整个订阅呢?下面是一个简化的示例代码,供您了解情况 .

我正在导入以下数据:

import { Observable } from 'rxjs';

在构造函数中,我准备了我的Observable:

this.myObservable = new Observable( observer => {
  observer.next( this.funcOne(observer) );
  observer.next( this.funcTwo(observer) );
  observer.next( this.funcThr(observer) );
  observer.next( this.funcFor(observer) );
  observer.complete();
} );

并且(下面)使用“subscribe()”方法,我开始订阅:

this.subscription = this.myObservable.subscribe( x => {
  if( x === -1 )
    this.subscription.unsubscribe(); 
    // I was thinking to unsubscribe here, but that doesn't work. 
    // I get a message saying: Cannot read property 'unsubscribe' of undefined
  else
    this.doSomethingElse(x)
} )

如何通过取消或取消订阅来完全停止一切?希望我的问题很清楚,谢谢你花时间阅读我的挫败感 .

1 回答

  • 0

    虽然我不太了解您对流的使用,但取消订阅的一种方法是保持一个布尔类型的主题并使用takeUntil(或管道(takeUntil),具体取决于您的rxjs版本),当您想要停止订阅时可以在该主题上执行.next(true) . 这将结束订阅 . 例:

    private destroy$ = new Subject();
    ...
    this.subscription = this.myObservable.pipe(takeUntil(this.destroy$)).subscribe( x => {
      if( x === -1 )
        this.destroy$.next(true); 
        // I was thinking to unsubscribe here, but that doesn't work. 
        // I get a message saying: Cannot read property 'unsubscribe' of undefined
      else
        this.doSomethingElse(x)
    } )
    

    希望这可以帮助 .

相关问题