javascriptrxjsrxjs-observablesrxjs-pipeable-operatorsrxjs-pipe

How to split an array and put values to observable-block?


There are some stream. This stream generate array. This array consists from a lot of numbers. I need filter these numbers and put to subscribe-block several apart values.

of([1, 2, 3, 4, 5, 6])
  .pipe(
    filter((val) => val < 5)
  )
  .subscribe((data) => console.log(data));  // 1--2--3--4--

Live demo is here.


Solution

  • We use from to convert the array into a stream of observables.

    We use switchMap to switch from the observable containing array of numbers, to from which emits each number.

    Finally we use filter array JS method, to filter the desired values.

    import { of,from } from 'rxjs';
    import { switchMap } from 'rxjs/operators';
    
    of([1, 2, 3, 4, 5, 6])
      .pipe(
        switchMap((items: number[]) => {
          return from(items.filter((v: number) => v < 5))
        })
      )
      .subscribe((data) => console.log(data));
    

    Stackblitz Demo