Sampath
Sampath

Reputation: 65860

Handle condition within Pipe RxJS

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) },
          };
        }
      });

Upvotes: 1

Views: 229

Answers (2)

Fateh Mohamed
Fateh Mohamed

Reputation: 21357

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)))
);

Upvotes: 0

vadimk7
vadimk7

Reputation: 8285

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) } }
  ),
);

Upvotes: 2

Related Questions