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?
-
2In 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.– Bryan RaynerNov 30, 2016 at 22:52
Add a comment
|
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();
}
});
-
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
-
-
2I 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 -
1Arrays implement Observable too so you can just write that as
.flatMap(x => x % 2 == 0 ? [x * 10] : [])
– phauxOct 6, 2016 at 10:24 -
2
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.