我正在使用 Rxjs。我有一个来自不同来源的 observable 和多个订阅。我希望在首次订阅 observable 后只触发一次函数。有没有办法实现这一目标?
不确定这是否适合您的情况,但我过去也处理过这个问题,发现最好在检查某种初始化变量后有条件地返回不同的可观察对象。下面是我的意思的一个工作示例。
this.statesService.getStates()
.subscribe((states) => this.states = states);
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。希望这为您提供了一些关于如何处理您的条件(仅在第一次订阅)场景的想法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句