Building a Stock Ticker

Let's build a stock ticker project, which displays stock prices in real-time.

Stock ticker project

In the previous few lessons, we built a typeahead. It covers only one kind of asynchronous flow. The frontend always triggers the initiating event and then waits for a response.

The backend never provides new data unless the frontend specifically asks for it.

In the next few lessons, you’re going to build a stock market viewer, which will display the (randomly-generated) prices of several fake stocks in real-time.

The server will send data to the frontend at any time, and the code needs to be ready to react to new events. In addition, the Rx stream needs to track the current state of each stock ticker for display on the page.

As a cherry on top to let you really flex your Rx muscles, we’ll add some on-page filters that require their own streams.

Constructor for web sockets

This is your biggest challenge yet. The first thing to write is the constructor. A constructor that’s specifically built for WebSockets in RxJS:

let endpoint = 'ws://localhost:3000/api/advancedAsync/stock-ws';
// No semicolon at the end here - this is continued in the next snippet
let stockStream$ = webSocket(endpoint)

đź“ť Subjects

stockStream$ isn’t a standard observable like you’ve seen so far, rather, it’s a Subject, an object that’s a turbocharged observable. For the purposes of this section, stockStream$ acts just like a regular observable. In Multiplexing Observables, you’ll learn about the other neat tricks subjects have up their sleeves.

Reducing streams using scan

So the graph of stock values can render the stock’s value changes over time; next, we need to record the last ten values this observable emitted. When a stream wants to accumulate values, you will turn to reduce or scan.

In this case, we want to use scan, because it emits a new value for every event on the stream, whereas reduce waits for the stream to complete. This stream never ends, so we use scan.

We can also use scan to accumulate a limited number of values by adding a check for the total length of the array. You need to adjust the data from time-based buckets into stock-based buckets with an extra map.

Get hands-on with 1200+ tech skills courses.