Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an RX method which combines map and filter?

Tags:

rxjs

I'm new to RxJS. I know I could just .filter and .map an observable to get the change I'm looking for. But, is there any method which combines the two into one function?

like image 718
Bryan Rayner Avatar asked Sep 07 '15 22:09

Bryan Rayner


2 Answers

Yes there is.

FlatMap.

Suppose you have an Observable of numbers (1, 2, 3, 4, 5, ...) and you want to filter for even numbers and map them to x*10.

var tenTimesEvenNumbers = numbers.flatMap(function (x) {
  if (x % 2 === 0) {
    return Rx.Observable.just(x * 10);
  } else {
    return Rx.Observable.empty();
  }
});
like image 157
André Staltz Avatar answered Nov 02 '22 22:11

André Staltz


As of rxjs v6.6.7, the solution becomes as following:

    // Initialise observable with some numbers
    const numbers = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

    // Pipe the observable using mergeMap
    const tenTimesEvenNumbers = numbers.pipe(
      mergeMap((x: number) => {
        // If the number is even, return an observable containing the number multiplied by ten
        // Otherwise return an empty observable
        return x % 2 === 0 ? of(x * 10) : EMPTY;
      })
    );

    // Subscribe to the observable and print the values
    tenTimesEvenNumbers.subscribe((value: number) =>
      console.log('Value:', value)
    );

The above will print:

Value: 20
Value: 40
Value: 60
Value: 80
Value: 100

Here is a working stackblitz as well.

like image 3
Michael Avatar answered Nov 02 '22 22:11

Michael