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

    Completing a Stream with TakeWhile

    John LindquistJohn Lindquist

    When you need to total up everything that has happened in your stream, you need to a way to tell your stream that it is “done”. This lesson covers how to use takeWhile to complete a stream.

    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 As it stands right now, our game will run forever. Once I hit start, and start scoring points, it's never going to stop. It's going to keep on counting. You might think you add another filter or something to make it stop, but filter does not trigger a complete event on our stream. Filter just tells our stream which things to put through.

    00:19 What we want is something called takeWhile, which will look exactly like a filter, so we'll say data. If we want our game to end after three seconds, we can say data count is less than or equal to three. Then, when we start our game, you can see we can do one, two, three.

    00:39 It's never going to score any points for anything beyond that. We also never see when our game actually completes if you want to do something when it's done. What you do there is subscribe actually takes three functions. This is the function that gets called every onNext or every tick.

    00:56 This one would get called if there's an error, so log out the error if an error happens. The third function is one that gets called once your stream is complete, so just log out complete. If I start my stream, I type one, and then wait until three. I'll get a point for three. It completes. Then I can never score again because my stream is done.

    Discuss

    Discuss