Vivek Kumar
Vivek Kumar

Reputation: 5040

How to combine operator input and result of defer operation together

I have tried to trim down my use case in below example.

I am stuck at the a point where I need to pass the result of operator which should have

so that I can use it next operator.

import { of, from, defer } from 'rxjs';
import { mergeMap, filter, concatMap, map, reduce } from 'rxjs/operators';

const list: number[] = [1, 2, 3, 4, 5, 6];

function testFunctionPromise(value: number) {
  return () => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        return resolve('processed-value ' + value);
      }, 1000);
    });
  }
}


from(list)
  .pipe(
    filter((item: number) => item % 2 === 0),
    concatMap((item: number) => {
      const pf = testFunctionPromise(item);

      /**
       *  QUESTION: from this step I want to pass both
       *  the result of defer(pf); and item
       * 
       *  as
       * 
       *  return { item: <result of defer(pf)> }
       * 
       */
      return defer(pf);
    }),
    reduce((acc: any[], item: any) => acc.concat([item]), [])
  )
  .subscribe(
    data => console.log({ data }),
    error => console.error({ error })
  )

url: https://stackblitz.com/edit/rxjs-defer?file=index.ts

Upvotes: 1

Views: 397

Answers (1)

martin
martin

Reputation: 96959

concatMap((item: number) => {
  return defer(testFunctionPromise(item)).pipe(
    map(result => ({
      item: result
    })),
  );
})

Or maybe if you want to use item as a property:

map(result => ({
  [item]: result
})),

Upvotes: 2

Related Questions