Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    What Is RxJS?

    Ben LeshBen Lesh

    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!

    rxjsRxJS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss