Both the Filter and Map rxjs
functions seem to be ways to manipulate a rxjs Observable
's stream. After tinking with them and from examples I've seen, they both seem to do the same thing.
What's the difference and when should I use one over the other?
Filter: Removes emitted data from the stream. Map: Transforms it.
RxJS filter() operator is a filtering operator used to filter items emitted by the source observable according to the predicate function. It only emits those values that satisfy a specified predicate. The RxJS filter() operator is like the well-known Array Array .
The map() operator's return value is observable that emits the values from the source Observable transformed by the given project function.
The Angular observable Map operator takes an observable source as input. It applies a project function to each of the values emitted by the source observable and transforms it into a new value. It then emits the new value to the subscribers.
They do the exact same as the corresponding Array
methods.
E.g.
const stream = Observable.of([1,2,3,4,5]);
stream
.map(x => x * 2)
.subscribe(x => console.log(x)); // 2,4,6,8,10
stream
.filter(x => x > 3)
.subscribe(x => console.log(x)); // 4,5
Maybe this site helps to understand the difference: https://www.learnrxjs.io/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With