Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading