Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS 6 conditionally pipe an observable

Tags:

I have an existing function which does some amount of work calling HTTP endpoints that takes care of managing some logic in my Angular component. A requirement comes in so that in a certain instance we need to all of the existing logic to be called, but also another HTTP call to be made. Below is an annotated version of my attempt.

public resolveComponent(action: string) {         //if called with no parameters, don't do anything         //otherwise, call one of the two endpoints.              let preAction = (x: any) => {             if (action === "replay") {                 return this.remediationService                            .replayRemediation(this.workflow.Id);             }             else if (action === "remove") {                 return this.remediationService                            .removeRemediation(this.workflow.Id);             }             else {                 return of([]);             }         }          this.remediationService             .resolveComponent(component)             .pipe(                 //the line below was what I added after new requirement                 mergeMap(preAction),                 mergeMap(x => {                     //grabs updated data from server                     return this.remediationService.remediationComponent(component.Id);                 })             )             .subscribe((x: SomeModel) => {                     //logic happens                 }); } 

This performs the work as expected, but is this the best way to go about conditionally chaining observables?

like image 794
wootscootinboogie Avatar asked Aug 15 '18 13:08

wootscootinboogie


People also ask

Does pipe subscribe to Observable?

A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output. Subscribing to the output Observable will also subscribe to the input Observable.

Does pipe execute Observable?

Using pipe to combine operators The order of the operators is important because when a user subscribes to an observable, the pipe executes the operators in a sequence in which they are added. To use observable we need it to import from the rxjs library.

What does pipe () do RxJS?

pipe() can be called on one or more functions, each of which can take one argument ("UnaryFunction") and uses it to return a value. It returns a function that takes one argument, passes it to the first UnaryFunction, and then passes the result to the next one, passes that result to the next one, and so on.


1 Answers

Use iif rxjs.

iif accepts a condition function and two Observables. When

  • an Observable returned by the operator is subscribed, condition function will be called.

https://www.learnrxjs.io/operators/conditional/iif

like image 64
Moslem Shahsavan Avatar answered Oct 25 '22 21:10

Moslem Shahsavan