Home > database >  RXJS conditional operator simplification
RXJS conditional operator simplification

Time:06-08

I have this working code:

import { timer, take, pipe, map, mergeMap, iif, of } from 'rxjs'

const double = () => {
  return pipe(
    map((x: number) => x * 2)
  )
} 

const triple = () => {
  return pipe(
    map((x: number) => x * 3)
  )
}

timer(0, 1000).pipe(
  take(4),
  mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))
).subscribe(x => {
  console.log('output', x)
})

Working stackblitz here

Output as expected is:

output 0
output 2
output 6
output 9

Only one question. This line is pretty verbose:

mergeMap(x => iif(() => x <= 1, of(x).pipe(double()), of(x).pipe(triple())))

Is it possible to simplify this line? Any help much appreciated. Many thanks.

CodePudding user response:

Instead of making double and triple custom operators, you could simply make them functions and just use map:

const double = (x: number) => x * 2;
const triple = (x: number) => x * 3;

timer(0, 1000).pipe(
  take(4),
  map(x => (x <= 1 ? double(x) : triple(x)))
);

If the modifications come from an observable source, you can use a function that returns an observable instead with mergeMap:

const double$ = (x: number) => of(x * 2);
const triple$ = (x: number) => of(x * 3);

timer(0, 1000).pipe(
  take(4),
  mergeMap(x => x <= 1 ? double$(x) : triple$(x))
);

StackBlitz

CodePudding user response:

It can be further boiled down to this

timer(0, 1000).pipe(
  take(4),
  map(x => x*(x <= 1?2 : 3))
);
  • Related