簡體   English   中英

首次訂閱 observable 的一次性操作

[英]One time operation on First subscription of observable

我正在使用 Rxjs。 我有一個來自不同來源的 observable 和多個訂閱。 我希望在首次訂閱 observable 后只觸發一次函數。 有沒有辦法實現這一目標?

不確定這是否適合您的情況,但我過去也處理過這個問題,發現最好在檢查某種初始化變量后有條件地返回不同的可觀察對象。 下面是我的意思的一個工作示例。

組件需要來自 API 的狀態列表

this.statesService.getStates()
    .subscribe((states) => this.states = states);

服務只想從 API 獲取一次狀態

    private _states: IState[];

    getStates(): Observable<IState[]> {
        if (!this._states) {
            // we don't have states yet, so return an observable using http
            // to get them from the API
            // then store them locally using tap
            return this.http.get<IState[]>('/options/states').pipe(
                tap((answer) => {
                    this._states = answer;
                }),
            );
        } else {
            // subsequent calls will just return an observable of the data needed
            return of(this._states);
        }
    }

在上面的例子中,很容易返回一個有條件的 observable。 希望這為您提供了一些關於如何處理您的條件(僅在第一次訂閱)場景的想法。

您可以使用 publishReplay(1)、refCount() 運算符。 它將確保僅評估一次 observable 並與所有訂閱者共享相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM