Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Filter Events Based on a Predicate with RxJS filter

    André StaltzAndré Staltz

    through a predicate function that tells what is the criteria to pass or reject an event. This lesson introduces filter: an operator that allows us to let only certain events pass, while ignoring others.

    rxjsRxJS
    ^5.0.0
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 The next operator we're going to see is Filter. Suppose we have an observable of numbers, like zero, one, two, three, etc., which is generated by that interval function above, and we would like to have only even numbers. We want to ignore out the odd numbers like one, three, five, seven, etc.

    00:22 We do that with Filter. It allows us to remove some of events by giving a function which is called a predicate. Predicate functions are simply they take an argument and they should return true or false. That's what a predicate function means.

    00:37 We return true when this X, which is the input event on this input observables, should pass. If it passes, it will appear here on the bottom. We return false when it should be ignored. In case of odd and even numbers, if the modulo of X with two is zero, then that's an even number, and this comparison would be true. That's why even numbers would pass.

    01:04 But if this modulo two with X would be one, then that means that we have an odd number, and that's why this comparison would be false, and the event would not pass. One does not pass, for instance. It would return false.

    01:20 Two would pass so the predicate would return true, and then etc., and we get an observable output at the bottom here with only even numbers. Let's call that in actual JavaScript. We take the modulo with two, check if it's zero, and then this is now observable bar.

    01:43 If we run this, we see that bar has only even numbers. Foo is ticking every second, but every other second it gives an odd number which we ignore. To recap, Filter allows you to pick certain events, and ignore others, through a predicate function that tells what is the criteria to pass or reject an event.

    Discuss

    Discuss