Home > Blockchain >  trying to chain http requests together and return the final output as an observable
trying to chain http requests together and return the final output as an observable

Time:11-03

While working in Typescript, i was having some issues with chaining observables together such that it made sense. So in this sample i wrote up, i a condition which will depending its value, will either execute a function or do some preprocessing before executing the function.

When doing this I was noticing that the problem area is attempting to return an Observable<Observable<number>> which isnt what I was aiming for. My thought was to return the inner value, but i was not sure how really to process this.

b(data: number): Observable<number> { return of(data); }  // This is a stub.
a(data: number): Observable<number> {

  const fn = (x): Observable<number> => {
    return of(x)  // this is a stub which would be the result of an http request.
  }

  if(data < 3) {
    return fn(data);
  } else {
    return b(data).pipe(map( x => fn(x) )) // Problem line
  }
}

How is this suppose to be processed? I was thinking that there might be a way to handle this using a Promise, but I thought that would mess with the function signatures as I would need to label them as async. I am stumped and would love some guidance.

CodePudding user response:

The issue you have is one condition returns an observable, while the other returns an observable that returns an observable. You should use one of the flattening operators such as switchMap, concatMap, or mergeMap.

return b(data).pipe(switchMap(x => fn(x)))

Maybe this could also benefit from a redesign? Instead having two separate returns, create a stream from the result of the conditional statement a pipe it to the function. This way you don't have to define a function just so you can use it in two places.

b(data: number): Observable<number> { return of(data); }  // This is a stub.
a(data: number): Observable<number> {
  const src$ = data < 3 ? of(data) : b(data);
  return src$.pipe(switchMap(x => of(x) /* your stub function */));
);
  • Related