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

问题描述 投票:0回答:1

如果状态为开始或停止,请订阅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();
    }
})
angular observable ngrx subscribe unsubscribe
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.