#Introduction to RxJS
Presented by Corinna Cohn February 17, 2016, IndyJS
##JavaScript is Asynchronous
JavaScript has an execution stack. Events are added to the stack and are executed in the stack order.
Callbacks for setTimeout, AJAX calls, or DOM events can happen at pretty much any time.
##Examples to think about
- Typeahead widgets
- Recording mouse input
- Timers
##Callback hell
This is callback hell.
getUserConfirm(function respondToAxax(response) {
if (response) {
validateData(data, function (nextResponse) {
var data = nextResponse.data;
saveEverything(data, function(success) {
if (success) {
alert('finished saving!');
}
});
});
}
});
##What is Reactive Programming
A style of programming that favors declarative specifications applied to data streams.
Declarative: the code describes the end result.
Data stream:
##What is RxJS?
Think of it like Lo-Dash for events streams.
- Observable
- Iterators
Works with:
- DOM Events
- Animation
- Ajax
- Websockets
##Why use Observable pattern?
-
Work on streams of data
- Events, Promises, timers, arrays
-
Are explicitly resolved
-
Multiple Subscribers can work with one Observer
-
Lazy execution
##Promises
- Good for when one call returns one value (AJAX)
- Are not cancellable.
##Examples
###Basic Observable Plunker
// Iterable object
const zooAnimals = ['anteater', 'bear', 'cheetah', 'donkey'];
// create the observable
const observable = Rx.Observable.from(zooAnimals);
// creating a subscriber will run the observable
const subscriber = observable.subscribe(
function onNext (animal) { console.log('animal: ' + animal); },
function onError(err) { console.log('Error: ' + err);},
function onCompleted() { console.log('no more animals!'); }
);
###Observable from Event
Plunker
###Observable from XMLHttpRequest
Plunker
###Angular 2 with RxJS Plunker
##Resources
The introduction to Reactive Programming you've been missing