What Is RxJS?

Ben Lesh
InstructorBen Lesh
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 6 years ago

RxJS Observables represent a collection of values over time, and can be accessed in familiar ways similar to arrays. RxJS can be thought of as underscore or lodash for asynchronous operations!

[00:04] To get started, I've already added my RX script to the page. I've switched jsbin to ES6 or Babel, so I have access to error functions and other ES6 features, and I've added this console clear so I don't junk up my console with my demo code. To understand observables, you need to understand a little bit about arrays. To demonstrate this, I'm going to create an array with a few values in it and I'm going to call a few of the array's higher-order functions like filter.

[00:36] I'll filter down to only the odd numbers, max, and I'm going to take my odd numbers and add an exclamation point to them, and finally for each where I'm going to log the results out to the console. If I run this, you'll see 1, 3, 5 and a very excited way with these exclamation points, and that's what we expected. Now an interesting thing about this, is observables are also collections. In fact, I can take my array and convert it to an observable.

[01:11] Observables have the same higher-order functions as an array. So when I run this, I get exactly the same result. Why is this interesting? It's because observables are asynchronous. They actually represent any number of values over any amount of time. To demonstrate this I'm going to create an interval of about a half second, and I'll only take six of those for demonstration purposes. An interval actually increments a number and emits that.

[01:44] When I run this now, you'll see they come in over time. But I didn't change this code down here at all. The reason this is interesting is if I had a function that accepted an array, and did this to it, I could change that function to accept an observable instead and now all of a sudden, my function can handle things asynchronously.

[02:12] That filter, map, and for each are just the tip of the iceberg for RxJS. RxJS observable has a lot more higher-order functions such as zip, merge, concat, that you might find in a library like underscore, or lodash making RxJS, underscore, or lodash for asynch.