代码之家  ›  专栏  ›  技术社区  ›  Sithys

在再次触发间隔之前取消订阅可观察的

  •  1
  • Sithys  · 技术社区  · 7 年前

    我正在开发一个角5应用程序,在这里我有一个像这样的可观察的应用程序:

    Observable.interval(10000)
        .takeWhile(() => !this.zeServerIsOnline)
        .subscribe(i => { 
            this.systemService.isServerOnline().subscribe(data => {
                if(data.success) {
                    this.zeServerIsOnline = true;
                    this.serverPolledForState = false;
                    if(this.bookingsInStorage > 0) {
                        this.allBookingsSubmitted = false;
                        this.sendSavedBookingsToServer();
                    }
                }
            }, error => this.isServerOnlineFailed(error));
        });
    

    我首先想到,当我的布尔值 this.zeServerIsOnline 变为真,但它被取消订阅,当10秒结束,可观察到的识别出我的布尔值的状态( 此.zeserverisonline )是真的。

    如果我现在意识到我的服务器又在线了( this.zeServerIsOnline = true ,我开始传输数据(我认为这是一个地方,当可观测数据被取消订阅时),但是现在,当服务器再次离线,而我传输数据时,10秒并没有超过我的可观测触发器,因为它无法识别 false true .

    只有当我的服务器在线时间超过10秒时,我的Observable才会被取消订阅。所以它一定与间隔有关,但我如何直接取消订阅,何时 此.zeserverisonline 真的吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   coder Flo We    7 年前

    创建变量类型 ISubscription

    subscription: ISubscription;
    

    我们认为你需要退订 this.systemService.isServerOnline() . 你可以这样做:

    this.subscription = this.systemService.isServerOnline().subscribe(data => {
                if(data.success) {
                    this.zeServerIsOnline = true;
                    this.serverPolledForState = false;
                    if(this.bookingsInStorage > 0) {
                        this.allBookingsSubmitted = false;
                        this.sendSavedBookingsToServer();
                    }
                }
            }, error => this.isServerOnlineFailed(error));
    

    或者如果你需要退订 Observable.interval(10000) 你可以这样做:

    this.subscription = Observable.interval(10000)
          .takeWhile(() => !this.zeServerIsOnline)
          .subscribe(i => {
            this.systemService.isServerOnline().subscribe(data => {
              if (data.success) {
                this.zeServerIsOnline = true;
                this.serverPolledForState = false;
                if (this.bookingsInStorage > 0) {
                  this.allBookingsSubmitted = false;
                  this.sendSavedBookingsToServer();
                }
              }
            }, error => this.isServerOnlineFailed(error));
          });
    

    现在您可以直接取消订阅:

    this.subscription.unsubscribe();
    

    您可以用这种方式直接取消订阅任何订阅。

    希望这对你有帮助!