RxJS pipe chaining with IF statement in the middle
12,607
Just instead of map
use one of its variants that work with Observables like concatMap
or mergeMap
(switchMap
will work as well in this situation):
getFirstValues$.pipe(
concatMap(data => {
if (data.length === 0) {
// this line is the one I have a problem with
return this.processedStockApi.getDefaultValues();
} else {
// this line returns fine
return of(data);
}
}),
switchMap(data => this.apiCall.doSomethingWithData(data)),
).subscribe(...);
Note that both if-else
blocks now return Observables. It's concatMap
who subscribes to them and emits their result further.
Author by
Alfa Bravo
Updated on June 17, 2022Comments
-
Alfa Bravo almost 2 years
I am getting a value, and based on the return, if data actually returned the first time I just send it through and carry on, else if nothing returns I get default values and carry on with the data.
My problem is returning the default data after the IF statement. I can not get it to return the data, instead of the observable/subscription
It looks something like this:
getValuesFunction() { const getFirstValues$ = this.ApiCall.getFirstValues(); this.subscription = getFirstValues$.pipe( map(data => { if (data.length === 0) { // this line is the one I have a problem with return this.processedStockApi.getDefaultValues().subscribe(); } else { // this line returns fine return data; } }), switchMap(data => this.apiCall.doSomethingWithData(data)) ).subscribe(); }
// ApiCall
getDefaultValues() { return this.http.get<any>(this.stockUrl + 'getSelectiveDeleteData'); }
-
Alfa Bravo over 5 yearsVery nice, they say to just learn a new operator every few weeks, and it seems I have now learned concatMap :)
-
jcdsr over 2 yearsjust make sure to understand that throwError() is not throw error medium.com/angular-in-depth/…