Search code examples
angularrxjs

RXJS - Conditional in switchMap operator for first or subsequent execution


My http fetch method in the service has a parameter "showLoadingSpinner". When it's set to false, the HttpContext DISABLE_LOADER_FOR_REQUEST = true will be set.

I want to set the showLoadingSpinner to false for every subsequent call but not for the first one:

First Call: show Loading Spinner
Next Calls: Don't show the Loading Spinner

Now I need a conditional inside the pipe in my components method, if it's the first service call or not, without creating a additional state variable.

What I don't want to have:

isFirstCall = true;

fetchData(): Observable<Bla> {
    return this.reload$.pipe(
        switchMap(() => this.service.fetch(this.isFirstCall),
        tap(() => this.isFirstCall = false)
    );
}

What I want to have:

fetchData(): Observable<Bla> {
    return this.reload$.pipe(
        switchMap(() => this.service.fetch(<here should be a conditional based on a RXJS operator, if it's the first emission or not>)
    );
}

Is there an operator from RXJS which I can use for it?


Solution

  • You could use the index of switchMap rxjs operator to know if it is the first emission or not.

    fetchData(): Observable<Bla> {
        return this.reload$.pipe(
            switchMap((_, index) => this.service.fetch(index)
        );
    }