21

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?

1
  • 3
    In retrospect, there's almost no reason to try and use filter and map as a single operation. If anyone else is "new to RxJS" and sees my question, don't take any of these answers. Just filter, and then map. Nov 30, 2016 at 22:52

3 Answers 3

32

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();
  }
});
9
  • Thanks for the answer - I never would have recognized that you could do this from the docs on flatMap. I'm selecting @paulpdaniels answer though because, it is more functional. Sep 8, 2015 at 13:43
  • You mean more functional in what sense? Sep 8, 2015 at 14:07
  • 2
    I mean that in this example, the filter operation must be done in the parens of the if statement. Say you have a common filter function that you'd like to apply to the operation many times, you could still do it, but you're left writing multiple if() statements. Additionally, you'd need to invoke it each time. It's much cleaner to have a solution where you can pass the filter and map functions in as separate arguments. In my mind, a solution which enables that style of coding is more 'functional'. Sep 9, 2015 at 14:02
  • 1
    Arrays implement Observable too so you can just write that as .flatMap(x => x % 2 == 0 ? [x * 10] : [])
    – phaux
    Oct 6, 2016 at 10:24
  • 2
    flatMap is now mergeMap: github.com/ReactiveX/RxJS/issues/333 Apr 5, 2017 at 20:45
7

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.

0

You can achieve this with a higher order function.

For example, here is a non-RxJS function to do the heavy lifting of producing the desired list. It takes two functions, the filter and map functions and returns a function that takes the list you are interested in processing.

function filterMap<A, B>(filterFn: (a: A) => boolean, mapFn: (a: A) => B): (as: A[]) => B[] {
   return (as) => as.reduce((acc, a) => {
     if (filterFn(a)) acc.push(mapFn(a));
     return acc;
   }, []);
}

You can ignore the types if using plain javascript.

filterMap can then be used like this:

const isEven = (a) => a % 2 === 0;
const doubleValue = (a) => a = 2 * a;
const doubleEvens = filterMap(isEven, doubleValue);
const myResult = doubleEvens([1, 2, 3, 4, 5);

Now you can use filterMap either directly in a rxjs map or define a new pipe function. Here is an example use:

of([1, 2, 3, 4, 5]).pipe(
  map(doubleEvens)
).subscribe(console.log);

There a couple of advantages

  • You can reuse filterMap to define any combination of filter and map you need
  • The operations can be given meaningful names
  • The list is iterated once
  • No extra observables are created
1
  • @judos had a comment about only mapping over only a subset and also keep the values that don't match. Solutions: 1) Just use map 2) define filterApplyMap similar to filterMap but add else clause and do acc.push(a) the final return type will be (A|B)[], same as #1, which is not that pretty 3) define filterPartitionMap which takes a pair of lists as the accumulator and pushes the appropriate value onto the appropriate list. Return type will be [A[], B[]]. I put B[] on right to be consistent with "true" value is on right.
    – SteveC
    Oct 26 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.