Check out a free preview of the full Rethinking Asynchronous JavaScript course

The "Observables" Lesson is part of the full, Rethinking Asynchronous JavaScript course featured in this preview video. Here's what you'd learn in this lesson:

While observables do not currently exist in the JavaScript specification, third-party libraries have begun implementing them. After introducing the concepts behind observables, Kyle demonstrates how use the RxJS library from Microsoft. He shares code that wraps an observable around a button’s click event.


Transcript from the "Observables" Lesson

>> [MUSIC]

>> Kyle Simpson: Enter observables. Now, understand that Observables are not a guarantee for JavaScript. Right now they are implemented in user-land libraries, and there is a proposal for Observables to land in the language. At some point, there was a strong feeling that they might land in the ES7 time frame.

As far as I'm aware, I don't think that's actually gonna happen in the ES7, meaning ES2016. Because as far as I'm aware as of today, I think the feature cut off for ES2016 is like next month. So Observables are on a good path and there's a pretty good chance we're going to get something like this natively in the language.

It just might not be next month. So it might be a little bit further off. And that means that what we're about to learn with Observables, we're learning based upon the semantics of a particular library implementation. We don't have a very good sense of exactly what they're going to be from a native primitive perspective, like we did with promises.

So the caveat here is the sorts of stuff that we're about to talk about is subject to some flux, it's subject to some evolution between now and the time that some final standard lands Observables may end up being called something different. They might have a different looking API, who knows, but right now there's a pretty good library out there for Observables and it's called RX J.S. that's our JavaScript library it's actually RX is the name of the library read reactive extensions.

It's made by the folks really smart folks at Microsoft, and they've ported it to like a dozen or a couple dozen different languages. So RXJS is the JavaScript port. It's in C. Sharp, I think that's the original one, it's in Java, it's in several other languages. So it's nice from the consistency perspective, whatever language you work in there's probably an RX library for it.

Once you learn it, once you're gonna be able to use it in lots of places that's good. But to understand what an observable is, again from a conceptual perspective, see this is how I always teach, I'm gonna teach you the API first, I wanna teach you the conceptuals.

So let's talk about spreadsheets. Everybody loves spreadsheets, right? I just found some random spreadsheet image on Google Images, cuz I don't have any good ones to take of my own. I don't know what the spreadsheet is, but it's pretty clear that this spreadsheet is illustrating the concept that I want to get across.

By the way, this metaphor is not unique to me. So I've heard this from others. I just think it's a particularly good one to start with. And observable is kind of like a chain of calculated fields in a spreadsheet. So you know in spreadsheets you can have data in a field.

But you can also have a field, which is a calculated field. It's calculated based upon the data that's in some other field. So C1 might have the number ten in it, and C2, right below it might be whatever the values in there times two. So when I type in 10, then as soon as I hit enter, immediately this field says 20.

And I might have another field over here, I might have D13 that says, D13 is the calculation of three times whatever's in C2. So I changed this to 20, C1 becomes 20, C2 becomes 40, and D13 becomes 120, right? Do you see that the calculation chain is a flow of data?

We're setting up a flow of data from an original source location to all these different places, where we're doing something with that data. We're calculating something. We're subscribing to and responding to that data. That's the genesis of this notion of reactive programming. When we think about reactive programming it is to say, the source of my data some of that source.

But the data once I get that event, it's going to go through a series of steps and some of those steps are going to be direct like responsive just calculate something and some of them might be asynchronous steps. The calculation of the data that goes through the spreadsheet as you change one value, even though it looks immediate to us.

Each step it has to update all the fields and then update all the fields and then update all the fields, so there is some propagation delay if you will. But we can think about an observable or rather reactive programming as a way to model a piece of data coming in one side, that's from the producer.

The event emitter, if you will, coming in one side, and all the steps that it takes to propagate its way through a system. It's a data flow mechanism, and data flow mechanisms are built from the ground up to respond to events. So if we've got a vent oriented systems, this might be a really good abstraction for us.

Is everybody following where I'm coming from conceptually. So we'll boil this down for you. An observable is an adapter hooked onto an event source that produces a promise, every time a new event comes through. But it does so in that separate way, where I can set up my event source.

And an entirely different part of my location, I can declaratively say, what's my data flow? I don't have to conflate the two like we're doing in those other examples, where I put the promise inside of the event thing. I have an observable that represents my data source and I can subscribe to that observable in one or more other locations of my system in an entirely separate way.

And it's going to magically take care of all that creation of promises in the bridge and the gap for us. So it's a way in programming to represent what we can visually think about, or conceptually think about from a spreadsheet. We can represent each one of those different fields as a different step in a chain of response to an observable.

So here's a quick example of some code from our RxJS, you'll notice that you create an observable using Rx.Observable.fromEvent. That's one of their many utilities they provide and the way it's set up is, it takes the dawn elements an event name it automatically hooks the event name to the dawn element and every time one of those events fires it pumps another piece of data through the chain, through the observable.

So that's how we create an observable from an event. There's about a dozen or so different ways to make an observable. You can make one by attaching it to an event. You can make a plain old simple observable that you manually are gonna put some data through, you can attach it from a website, I mean there's a lot of different ways to make observables.

But I make an observable on line one, in an entirely different part of my system. I can declare what all those steps are, what all the calculations of the fields in my spreadsheet look like. Basically, I make a declarative chain of the data flow. So every time an event comes in from the DOM event, every time I click on a button that's a piece of data coming in and it's going to flow through this chain.

Now, we have utilities that look familiar to us like map. Map in the synchronous sense went over a whole array of the values. Map in the asynchronous event is just invoked every time a new piece of data comes along. So you can actually think about an event stream as a never ending array.

And we can perform the same sorts of list operations across time that we would do all together. That's why it was important for us to understand maps and reduces and things like that. So here, we can map over an event stream in much the same way conceptually that we could map over an array that was already complete.

It's just that every time a piece of data comes through, we can do some sort of transformation on it. And here the transformation is I'm extracting the class name from the event object, okay. We can filter down, we can do perform an exclusion on our list. And that's something interesting.

Because fundamentally, fundamentally this list is actually asynchronous. We can actually have steps in our response that are asynchronous. Distinct until changed. It's an interesting one. What it says is, the first time a piece of data comes through, let it go through. But if another one comes through the same piece of data, don't let that go through because I've already seen that one, but then if something new comes along.

Let that one through. And if I keep getting the same one of those, don't let any more duplicates come through. So let's say, I have one that the number one comes to the system and I got five of those, only the first one is going to be let through in the next four going to be ignored.

And then a two comes along. So I'm going to let the first two come along at any duplicates are going to be ignored. What happens when another one comes along? I'm going to let a one one more one come through and then ignore any duplicates that's what the until changed is.

So there's distinct which is just I only want one ever of the thing and distinct until changed is distinct, and then I reset every time a new value comes in. I reset what I'm remembering. So you notice in this chain, not all of my events are going to make it to line 11.

And that's totally okay, cuz we're setting ourselves up with a data flow, just like we would in a spreadsheet. Subscribe is kind of like the end of the chain. Subscribe is how you basically have a sort of synchronous response to any events that are coming in. So there's more to it than that.

But you notice that basically subscribe is kind of like a synchronous thing. I'm not transforming any data, it's not really gonna show up in the middle of my chain, probably. It's kinda be at the end of my chain, it's when I and finally done with whatever the data is through all of its transformations and filterings I arrived at some data.

So at the end of my chain, I have a subscribe of a piece of data that comes in and I can console.log it out.
>> Kyle Simpson: Okay. That's a real high level view of what working with an observable is like. We have to make an observable some way and we have utilities, and libraries that can do that for us, and then we have to respond to observables.

And it's appropriate, I think, some people disagree with this, but I think it's appropriate to think of an observable as a stream. It's a stream of data that's gonna come through. It's being pumped by a set of events and it's a stream of data that's coming through.
>> Kyle Simpson: So what about distinctUntilChanged, I actually want you all to pop this up.

You have in your slides the link or you can just type, I love this website Let's all take a look at, I just get such a kick out of this web site.
>> Kyle Simpson: Let me quickly orient you, go ahead and click down on the distinctUntilChanged which is just slightly down the list there on the left.

Click on the distinctUntilChanged. And you'll notice that it's depicting for us what these marbles these little bubbles here, kind of exactly we're talking about the touch the stuff on the top is the input. And there's only one stream for this. And the stuff on the bottom is the output.

And you notice what happens, as I start to move these marbles around. What happens if I move this one over here, the solid just disappear because the sequence meant that it was just a duplicate. So we can move the marbles around and see how these different stream operations operate.

We're going to come back to RxMarbles and look at more stream operations and a little bit, but you can notice that probably about the top. I'd say maybe 30 or 40 of them are depicted here. Rx actually has probably like 150, maybe 200 different methods it's a pretty big library.

All told, if you've got everything, I think it's something like 150, 200k of JavaScript. So it's a pretty stout library. It takes a while to learn all these things. I have not found any other resource on the web that is better at learning than RxMarbles, I think you can probably learn probably 50% of Observables by doing nothing but just playing around with the bubbles on the screen.

It's a really fantastic resource. Okay. Helps you visualize what's happening with your different stream operations. So we'll come back to distinct until change, I mean we'll come back to RXmarbles here in a little bit. I just wanted to point that out to you.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now