RxJS Hands-on
Reactive programming
Reactive extensions for JavaScrips (a.k.a RxJS)
Before web begin ...
A Reactive system is
A programming paradigm concerned with streams and the propagation of change to simplify the creation of interactive user interfaces and real time system animation
A sequence of ongoing events ordered in time
Data streams can be anything :
Arrays, DOM Events, Network request (sockets, Ajax), Animations...
[
]
Are like arrays
1s
2s
4s
7s
8s
End
Time
But they can be asynchronous
Error
9
20
8
7
10
Time
Time
Time
Data provider (REST API, WebSocket server, ...)
Time
Value
Error
completed signal
could be filtered and concatenated...like any other collection
Thanks to > Operators
RxJS
Key concepts
(formerly called streams in reactive programming)
Single value
Multiple value
Not lazy
Cancelable
Lazy
Completion callback
Cannot be cancelled
Catch, Finally
const source$ = new Rx.Observable(observer => {
observer.next('foo');
observer.next('bar');
observer.next('baz');
observer.complete();
});
const source$ = new Rx.Observable.create(observer => {
observer.next('foo');
observer.next('bar');
observer.next('baz');
observer.complete();
});
// From one or multiple values
Rx.Observable.of('foo', 'bar');
// From array of values
Rx.Observable.from([1,2,3]);
// From an event
Rx.Observable.fromEvent(document.querySelector('button'), 'click');
// From a Promise
Rx.Observable.fromPromise(fetch('/users'));
synchronous observables
const source$ = Rx.Observable.of('foo', 'bar', 'baz');
const observer = {
x => console.log(x),
err => console.error(err),
() => console.info('done')
};
source$.subscribe(observer);
Observer is an object with next, error and complete methods
const subscription = source$.subscribe({
x => console.log(x),
err => console.error(err),
() => console.info('done')
});
const source$ = Rx.Observable(observer => {
let timeoutId = setTimeout(() => {
observer.next('You will never see this message');
}, 2000);
return onUnsubscribe = () => {
clearTimeout(timeoutId);
}
});
let subscription = this.data.subscribe(
value => this.value = value,
error => console.log(error),
() => this.status = 'Finished';
);
setTimeout(() => {
subscription.unsubscribe();
}, 1000);
Buffer, FlatMap, GroupBy, Map, Scan, Window, ...
Debounce, Distinct, Filter, First, Last, Skip, SkipLast, Take ...
Join, Merge, Switch, Zip, ...
Operators by category
A Subject can act as both — a data producer and a data consumer
Can be subscribed to, just like an observable
Can subscribe to other observables
const observable = Rx.Observable.from([0, 1]);
observable.subscribe(subject);
const subject = new Rx.Subject();
subject.subscribe(v => console.log('consumer A: ' + v));
subject.subscribe(v => console.log('consumer B: ' + v));
subject.next(1);
npm install rxjs
const { Observable } = require('rxjs/Rx');
Observable.of(1,2,3);
require('rxjs/add/observable/of');
require('rxjs/add/operator/map');
You loved the workshop ? give us your feedback