Introduction to RxJS

1 min readWeb Development

1 · a plain array, higher-order functionssource arrayfilterkeep the odd onesmapedit the resultforEachprint eachoutput, synchronously2 · the same steps over an ObservableObservableover the arrayfiltermapforEachthe same output3 · interval(500) with take(6): asynchronous00.5 s11.0 s21.5 s32.0 s42.5 s53.0 semits"RxJS = Observables + Operators + Schedulers", the definition the post quotes.
The three fiddles the post walks through, as its text describes them: the array run through filter (odd values), map and forEach; the same three steps over an Observable, giving the same output; and interval(500) with take(6), which emits 0 to 5 one every half second, which is where the asynchronous behaviour shows. The fiddles themselves are embedded in the post.

First thing first - What is RXJS ?

"The Reactive Extensions for JavaScript (RxJS) is a set of libraries for composing asynchronous and event-based programs using observable sequences and fluent query operators that many of you already know by Array#extras in JavaScript. Using RxJS, developers represent asynchronous data streams with Observables, query asynchronous data streams using our many operators, and parametrize the concurrency in the asynchronous data streams using Schedulers. Simply put, RxJS = Observables + Operators + Schedulers."

So, lets understand this with a peace of code. We have an array named source and on it we apply higher order functions like Filter (to get the elements which are odd), Map (to edit the result) and finally ForEach loop (where we will iterate through each element and print it to the result.).

So far so good, here is the output -

Now, lets add the Observable feature of RxJS. This Observable feature is defined to make things asynchronous. So lets try it.

We applied the same higher order function, but observed the same output. Wondering why .? Lets see another code -

Did we just observe the asynchronous behavior. Lets understand the code. We have an interval set of 500 over a take of 6 (0,1,2,3,4,5) This interval when defined using observable, makes sure that the instance runs asynchronously within the defined interval.

Example taken from - Egg Head Read more about RJS - Click Here