Home > Software engineering >  Handle condition within Pipe RxJS
Handle condition within Pipe RxJS

Time:10-11

I have this kind of Observable and I can easily use the async pipe on the template with this.

leadChanged$: Observable<LeadModel>;

this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
          map((res) => ({
            ...res,
            alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
          }))     
        );

But due to extra logic where now I need to write above like so: The logic is this res?.isManualLead. Do you know how to use this without a subscribe here? i.e. I want to use the async pipe here too.

leadChanged: LeadModel;

this.leadsDataService.leadChanged$
      .subscribe((res) => {
        if (res?.isManualLead) {
          this.leadChanged = {
            ...res,
          };
        } else {
          this.leadChanged = {
            ...res,
            alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) },
          };
        }
      });

CodePudding user response:

How about condition inside the map operator?

this.leadChanged$ = this.leadsDataService.leadChanged$.pipe(
  map(res => res?.isManualLead
    ? { ...res } 
    : { ...res, alert: { ...res.alert, transcript: highlightKeywordsLeadFunction(this.lead) } }
  ),
);

CodePudding user response:

you can subscribe to first or second observable based on a condition sing iif rxjs operator

import { iif, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
...

this.leadsDataService.leadChanged$.pipe(
  mergeMap((res) => iif(() => res?.isManualLead, of({ ...res }), of(anotherValue)))
);
  • Related