This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Completing a Stream with TakeWhile

1:19 RxJS lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

Avatar
G

Getting a rather strange error from the changes in this episode.

Uncaught TypeError: Rx.Observable.combineLatest(...).takeWhile is not a function

I'm using the RxJS 5.0.0-alpha.8 build on jsbin.com, but I can't find anything that would indicated an issue with takeWhile being used.

In reply to egghead.io
Avatar
G

Hmm, even downgrading to the stable rx.all 4.0.6 gives a new error

Uncaught TypeError: start$.mapTo is not a function

From the starters$ Observable

const starters$ = Rx.Observable.merge(
    start$.mapTo(1000),
    half$.mapTo(500),
    quarter$.mapTo(250)
);
In reply to G

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.

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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?