首次订阅可观察的一次操作

时间:2019-05-02 13:06:25

标签: javascript angular rxjs observable ngrx

我正在使用Rxjs。我有一个来自不同来源的可观察的订阅。我希望在首次订阅可观察对象后仅触发一次功能。有什么办法可以做到这一点?

2 个答案:

答案 0 :(得分:1)

不确定是否适合您的情况,但我过去也曾对此进行过处理,并发现最好在检查某种初始化变量后有条件地返回另一个可观察的对象。以下是我的意思的有效示例。

Component需要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);
        }
    }

在上述情况下,很容易返回条件可观察值。希望这可以为您提供一些有关如何处理条件(仅在首次订阅时)方案的想法。

答案 1 :(得分:-1)

您可以使用publishReplay(1)和refCount()运算符。它将确保仅评估一次可观察的结果,并向所有订阅者共享相同的结果。

相关问题