Alfa Bravo
Alfa Bravo

Reputation: 1991

RxJS pipe chaining with IF statement in the middle

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

Upvotes: 8

Views: 22781

Answers (1)

martin
martin

Reputation: 96969

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.

Upvotes: 10

Related Questions