【问题标题】:Unsubscribe from observable before interval fired again在间隔再次触发之前取消订阅 observable
【发布时间】:2018-07-19 14:25:10
【问题描述】:

我正在开发一个 Angular 5 应用程序,其中我有一个像这样的 Observable:

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 秒结束并且可观察对象识别我的布尔值 (this.zeServerIsOnline) 的状态为真时.

所以,如果我现在认识到,我的服务器再次在线 (this.zeServerIsOnline = true),我将开始传输数据(并且我认为这是一个地方,当 observable 被取消订阅时)但是现在,当服务器运行在我传输数据时再次离线,并且我的 Observable 触发器没有超过 10 秒,因为它无法识别从 falsetruefalse 的切换。

只有当我的服务器在线超过 10 秒时,我的 observable 才会被取消订阅。所以它必须有某物。与时间间隔有关,但是当this.zeServerIsOnline 为真时,我如何直接取消订阅?

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    创建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();
    

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

    希望对您有所帮助!

    【讨论】:

    • 感谢您的回答编码器,我是 rxjs 的新手,所以我应该触发 10 秒的间隔而不是那个订阅?所以我需要每 10 秒调用一次并取消订阅,而不是在我的 this.sendSavedBookingsToServer() 函数中。
    • 您可以将interval(10000) 订阅到this.subscription 变量中,并在this.sendSavedBookingsToServer() 函数中使用this.subscription.unsubscribe(); 取消订阅它
    • @Sithys 很高兴听到这个消息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多