Merge RxJS Button Event Streams to Build a React Counter Component

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

Combining input streams then using scan to track the results is a common scenario when coding with streams. This lesson walks you through setting up two buttons and merging their input events together to build a streaming Counter component.

Instructor: [00:00] We'll wire up this counter with an on increment and on decrement handler. We can do that in a counter stream. Use component from stream. Get out props. To start with we'll just return the props and map the props to counter. Swap out our counter with counter stream. Have the same thing over here with... Button is not working obviously.

[00:22] We'll create two handlers. Our first is our create event handler. We'll get a stream and handler. Just duplicate this line. We'll call this one our on increment stream. The handler can be on increment. Then on decrement stream with the handler of on decrement.

[00:40] To properly wire this together, let's switch map our props over to an observable.merge. This observable merge is going to take our on increment observable mapped to one and our on decrement observable mapped to negative one. Then we can start with props.value and then we'll have to map the value to our new props, which can take in the value.

[01:10] From here we have the value showing up through the stream. Then we want to pass through the on increment and the on decrement as props. Hit save here. Right now, that will just change this to one. That will change this to negative one.

[01:24] We can go ahead and scan over these so that the accumulator and the current is simply the accumulator plus the current. It'll take the value and either add one or negative one.

[01:36] You can go from there. Click and go up. Click and go down.