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');
}
Prior to RxJS 5.5, you were dot-chaining the operators like this: RxJS 5.5 introduced pipeable operators and pipe: You can now easily build your own operators and chain them with the RxJS ones:
Deprecations & Breaking Changes RxJS is mostly useful for its operators, even though the Observable is the foundation. Operators are the essential pieces that allow complex asynchronous code to be easily composed in a declarative manner. Operators are functions. There are two kinds of operators:
This post is part of a series of blogpost on different RxJS patterns that I use quite often. Here are the other ones: The next pattern I want to discuss is executing conditional work. Sometimes, you have a stream and if some condition is met, you want to do some extra step. But, we do not have an if-else operator. And that makes sense.
The something () on line 2 wants to be called, but it's gated off by the if ( isSomething) on line 1. In other words, if statements (line 1) act a lot like filters. The RxJS version is just that: But the topic here is if/else, not just if.
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.
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