Completing a Stream with TakeWhile

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 6 years ago

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.

[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.