rxjsrxjs-observables

RXJS Operator that checks a condition and directly emits value if true


I am searching for an RXJS Operator that takes a stream of values and checks each value for a certain condition.
If this condition is true, all following operators should be ignored and the value should just be emitted as is.
If the condition is false, all following operators should be used normally.

So for example:

  const source$ = of(1, 2, 3, 4, 5);
  source$
     .pipe(
        theOperatorISearchFor((v) => v <= 4),
        map((v) => v + 100)
     )
     .subscribe((v) => console.log(v));

In this case my output would be: 1, 2, 3, 4, 105

The first 4 times my condition is true, so all following (the map operator) are ignored and the values are just emitted.
The last value does not fullfil the condition, so 105 is outputted.

Any idea?


Solution

  • There is no such operator. However, you could merge 2 different streams.

    const source$ = of(1, 2, 3, 4, 5);
    
    const [small$, high$] = partition(source$, (v) => v <= 4);
    
    merge(small$, high$.pipe(map((v) => v + 100))).subscribe((v) => console.log(v));
    

    Stackblitz: https://stackblitz.com/edit/rxjs-sqmj2m?file=index.ts