Search code examples
javascriptangularrxjsobservablengrx

One time operation on First subscription of observable


I am using Rxjs. I have one observable and multiple subscription from different sources. I wish to trigger one function only once after getting first subscription to the observable. Is there any way to achieve this?


Solution

  • Not sure if this fits your scenario, but I have dealt with this in the past as well and found it best to conditionally return a different observable after checking for an initialization variable of some kind. Below is a working example of what I mean.

    Component wants a list of states from an API

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

    Service wants to only get the states once from the 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);
            }
        }
    

    In the case above, it's easy to return a conditional observable. Hopefully this provides you some ideas on how to handle your conditional (only on the first subscribe) scenario.