如何检查是否已取消订阅可观察的角度

时间:2019-10-05 00:31:03

标签: angular observable ngrx subscribe unsubscribe

如果状态为开始或停止,请订阅autoRefreshEveryMinute可观察的

如果状态为运行,请订阅autoRefreshEveryFiveMinutes并取消订阅可观察到的autoRefreshEveryMinute

如果状态未在运行,请取消订阅autoRefreshEveryMinute和autoRefreshEvery5Minutes可观察到的

我通过设置getter方法中的observable方法尝试了以下方法。

但是我意识到,即使已经订阅了可观察对象,它将始终在getter中调用subscribe方法。

可以调用一次吗?如何检查是否已经订阅了可观察对象?

 get isDMRunning() {
     const isDMRunning = !!this.details && this.details.status === StatusEnum.RUNNING; 
    // how to execute the if function only once, how to check that if already subscribed then we doesn't need to invoke it again?
    if (isDMRunning && this.autoRefreshEveryMinute) {
        this.autoRefreshEveryMinute.unsubscribe();

        // Polling details data every 5 minutes if is running
        this.autoRefreshEveryFiveMinute = interval(300000)
            .pipe(
                takeUntil(this.ngUnsubscribe)
            )
            .subscribe(() => {
                // Refresh page
                this.showDetailsLoading = true;
                this.loadDetails();
            });
    }
    return isDMRunning;
}

  get isDMStartingStopping() {
     const isDMStartingStopping = !!this.details && (this.details.status === StatusEnum.STARTING || this.details.status === StatusEnum.STOPPING);
    if (this.autoRefreshEveryFiveMinute) {
        this.autoRefreshEveryFiveMinute.unsubscribe();
    }
    // Polling details data every minutes
    this.autoRefreshEveryMinute = interval(60000)
        .pipe(
            takeUntil(this.ngUnsubscribe)
        )
        .subscribe(() => {
            // Refresh page
            this.showDetailsLoading = true;
            this.loadDetails();
        });
})

get isDMNotRunning() {
     const isDMNotRunning = !!this.details && (this.details.status === StatusEnum.NOTRUNNING);
    // the below if statement seems to invoked multiple times even though already unsubscribed from the observable
    if (this.autoRefreshEveryFiveMinute) {
        this.autoRefreshEveryFiveMinute.unsubscribe();
    }
   if (this.autoRefreshEveryMinute) {
        this.autoRefreshEveryMinute.unsubscribe();
    }
})

0 个答案:

没有答案