Home > Software engineering >  Retain values from rxjs operators
Retain values from rxjs operators

Time:12-21

I have a subject defined as below

this.checkListSubject
  .pipe(
    takeUntil(this._unSubscribeAll),
    filter((filter) => !!filter),
    switchMap((index) => this._api.get('getMyData')),
    tap((list) => this.gateEditArrayModal.toArray()[index].display(list))
  )
  .subscribe();

As I understand the tap cannot have the value of index because its lost after switchMap. There is any way to get the value of index in tap?

Thanks

CodePudding user response:

Yes, but you need to use a nested pipe. In the pipe you map the result into the original index together with the result

switchMap(index => this._api.get( 'getMyData' ).pipe(
    map(result => ({result, index}))
)),
// use the index
tap(({index}) => this.gateEditArrayModal.toArray()[index].display()),
// back to the result
map(({result}) => result),

CodePudding user response:

You can achieve that in different ways using other RxJS operators, such as map or withLatestFrom.

  1. Using the withLatestFrom operator instead of switchMap:
this.checkListSubject
  .pipe(
    takeUntil(this._unSubscribeAll),
    filter((filter) => !!filter),
    withLatestFrom(this._api.get('getMyData')),
    tap(([index, list]) =>
      this.gateEditArrayModal.toArray()[index].display(list)
    )
  )
  .subscribe();
  1. Using the map operator with switchMap:
this.checkListSubject
  .pipe(
    takeUntil(this._unSubscribeAll),
    filter((filter) => !!filter),
    switchMap((index) =>
      this._api.get('getMyData').pipe(map((list) => [index, list]))
    ),
    tap(([index, list]) =>
      this.gateEditArrayModal.toArray()[index].display(list)
    )
  )
  .subscribe();
  • Related