I have the following ngrx effect. Inside "map" I have a condition. How can I stop the effect immediately without continue to the mergeMap.
@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
  ofType('INIT_ACADEMY_DOMAIN'),
  map((action: any) => {
    const url = 'http://www.academy.xyzq';
    if (1 === 1) {
      // Make this effect stop immediately and do nothing more
    }
    action.url = url;
    return action;
  }),
  mergeMap((action: any) =>
    this.http.get(action.url).pipe(
      switchMap((data: any) => {
        return [{
          type: 'INIT_ACADEMY',
          payload: {
            academy: data.academy
          }
        }];
      })
    )),
  catchError(() => of ({
    type: 'INIT_IT_FAILED'
  }))
);You should consider using the filter function to filter out actions based on your condition:
@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
  ofType('INIT_ACADEMY_DOMAIN'),
  filter((x) => 1 === 1),
  mergeMap((action: any) =>
    this.http.get(action.url).pipe(
      switchMap((data: any) => {
        return [{
          type: 'INIT_ACADEMY',
          payload: {
            academy: data.academy
          }
        }];
      })
    )),
  catchError(() => of ({
    type: 'INIT_IT_FAILED'
  }))
);
Alternatively you could just dispatch a new action if your condition is true and create a simpler effect that executes the part inside your mergeMap function.
You should try to keep your effects as simple as possible. If your effect does a lot of logic / condition checks, it is hard to find a suitable name that captures what the effect really does.
You can try like this.
@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
  ofType('INIT_ACADEMY_DOMAIN'),
  map((action: any) => {
    const url = 'http://www.academy.xyzq';
    if (1 === 1) {
      // Make this effect stop immediately and do nothing more
      return null;
    }
    action.url = url;
    return action;
  }),
  mergeMap((action: any) =>
    if(action){
    return this.http.get(action.url).pipe(
      switchMap((data: any) => {
        return [{
          type: 'INIT_ACADEMY',
          payload: {
            academy: data.academy
          }
        }];
      })
      } else{
        return null;
      }
    )),
  catchError(() => of ({
    type: 'INIT_IT_FAILED'
  }))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With