Return switchMap inner results in an array like forkJoin

Issue

I want to run a set of observables one after another, since each result depends on the previous.
However, at the end I also need all the intermediate results, as they are given when we use forkJoin – in an array.

I have the following code:

     getData$ = getResponses$
            .pipe(
              switchMap((data_1) => {
                return getResponse_1$;
              })
            )
            .pipe(
              switchMap((data_2) => {
                return getResponse_2$;
              })
            );

getResponse_2$ depends on getResponse_1$ and
getResponse_1$ depends on getResponses$

I want the final results i.e. getData$ to be an array of the intermediate results (like forkJoin).
Is there such a way?

Solution

You can try something like the following:

// Let's consider that you have the following observables:
const getResponses$ = of('Text');
const getResponse_1$ = of(1);
const getResponse_2$ = of(true);

// The type of getData$ will be: Observable<[data: string, data_1: number, data_2: boolean]>
const getData$ = getResponses$.pipe(
  switchMap((data) =>
    getResponse_1$.pipe(map((data_1) => ({ data, data_1 })))
  ),
  switchMap(({ data, data_1 }) =>
    getResponse_2$.pipe(
      map((data_2) => {
        const res: [data: string, data_1: number, data_2: boolean] = [
          data,
          data_1,
          data_2,
        ];
        return res;
      })
    )
  )
);

Answered By – Amer

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.