Handling a Complete Stream with Reduce

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 4 years ago

When a stream has completed, you often need to evaluate everything that has happened while the stream was running. This lesson covers how to use reduce to collect values and total up a “score” of this simple game.

[00:00] To tally up our final score, there's operators that run on complete when a stream is complete, and one of them is Reduce. Reduce is just going to sit there and collect whatever comes through this stream until this stream hits complete. It's your basic accumulator current, and then some sort of expression. We'll say accumulator plus one, and then a starting point for the reducer.

[00:26] This is saying start with zero, and every time you're run, add one to the accumulator. Zero accumulates plus one would now be one, then two. We're just ignoring the current for now. The current would be this data that comes through, but we don't really need it to keep track of score.

[00:42] When I hit start, if I type one, two, three, if I got lucky, I scored all three points. Now let's try that again. I'll hit start. I'll miss one, I'll type two, three. I got two points. Let's see if I can only type a third second, so, one, two, three, and I got one point. You can see that's my final score because the reducer is pushing that through to the on next.

[01:13] The complete doesn't take any parameters. It's just now our subscribe block is waiting for the completion and getting the final reduced output.

~ 5 years ago

what's the difference between reduce and scan? It seems that they do the same thing, but reduce operator emits a value only when its source observable completes. Scan will spit out values all the time.

J. Matthew
J. Matthew
~ 4 years ago

Yes, I think that's right. scan lets you accumulate a value and make use of it throughout the life of a stream, like how we were incrementing the timer and logging it each tick in prior lessons. It doesn't notify you (or make itself available) once the stream completes. reduce lets you summarize the entire life of the stream once the stream completes, but you can't read or make use of the summary before that point.