【问题标题】:One time operation on First subscription of observable首次订阅 observable 的一次操作
【发布时间】:2019-05-02 13:06:24
【问题描述】:

我正在使用 Rxjs。我有一个来自不同来源的可观察和多个订阅。我希望在第一次订阅 observable 后只触发一次函数。有没有办法实现这一目标?

【问题讨论】:

  • 请提供一些代码,或者更好的stackblitz

标签: javascript angular rxjs observable ngrx


【解决方案1】:

不确定这是否适合你的场景,但我过去也处理过这个问题,发现最好在检查某种初始化变量后有条件地返回不同的 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。希望这可以为您提供一些关于如何处理有条件(仅在第一次订阅时)场景的想法。

【讨论】:

  • 是的。这真的很有帮助..会解决我的问题..非常感谢。
【解决方案2】:

您可以使用 publishReplay(1)、refCount() 运算符。它将确保只对 observable 进行一次评估,并与所有订阅者共享相同的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2016-09-25
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多