A Quick Observation on Observables

Schno Mozingo
2 min readMar 24, 2017

--

Observable? Whatever is an ‘Observable’?

Fair question.

To answer that, let’s start with thinking of an sweet, unassuming array. An array sits in memory, neatly defined with values and a length and can be accessed and manipulated by all the nifty array methods. Arrays are great for working with collections of data if you’ve got all the data you need to work with.

But… what if you needed to work with data that you don’t have yet? What if instead of a neat collection of data extant in memory, you’ve got to deal with a series of events that are firing in rapid succession? That’s where the magic of Observables come in to save the day. Think of an Observable as an array in the fourth dimension: the dimension of time!

An Observable, then, is any defined element that emits a stream of events: a button may emit ‘click’ events, a slider may emit coordinate update events on drag, etc.

When we subscribe to an Observable with an ‘Observer’, that observer reacts to whatever item or sequence of items that the Observable emits. This all happens asynchronously, so it doesn’t do any blocking of the rest of our code. It just hangs out and happily performs prescribed functions as instructed when new events are emitted by the observable.

For example, let’s say we wanted to throttle a button on our webpage that sends an ajax call on every click — an entirely reasonable thing to do, because some people are trolls that like to break websites.

We could create an Observable stream out of the click events from the button element and subscribe to that stream. As the mouse events are emitted into the source stream, we can apply any number of Observable ‘operators’ to that stream. In this case, obviously, we want to throttle it to foil the nasty troll. The resulting, de-trolled stream can now be the input to our function that makes the ajax calls. Pretty cool, eh?

This marble diagram shows the source Observable stream on top. Each event is processed through throttleFirst and the resulting stream is emitted on the bottom. Cool stuff!

--

--