reactive programming with rxjs
RxJS Hands-on
Reactive programming
Reactive extensions for JavaScrips (a.k.a RxJS)
Agenda
What does it mean
to be reactive ?
Before web begin ...
A Reactive system is
One that is in continual interaction with its environment
The Reactive Manifesto
defines reactive as
scalable
event-driven
resilient
responsive
Reactive programing
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 stream is
A sequence of ongoing events ordered in time
Data streams can be anything :
Arrays, DOM Events, Network request (sockets, Ajax), Animations...
StreamS
[
]
Are like arrays
1s
2s
4s
7s
8s
End
Time
But they can be asynchronous
Error
This is a Data Stream
9
20
8
7
10
Time
Time
This is aN EVENT Stream
Time
This is aN Asynchronous Stream
Data provider (REST API, WebSocket server, ...)
Time
StreamS propagate SIgNALS
Value
Error
completed signal
You need to subscribe to STREAM
And react to new SIGNALS
Streams
could be filtered and concatenated...like any other collection
You can combine streams together to build new ones
Thanks to > Operators
reactive extensions for
JavaScript
RxJS
Key concepts
it's all about OBSERVABLES
(formerly called streams in reactive programming)
- A set of any number of things over any amount of time
- Lazy and juste functions in JavaScript - they don't do anything until you subscribe to them
- Can be unsubscribed from
- Are always observed by observers
wait !
how you handle asynchronous calls today ?
promises
promises vs observables
Single value
Multiple value
Not lazy
Cancelable
Lazy
Completion callback
Cannot be cancelled
Catch, Finally
THE GENERAL THEORY OF REACTIVITY
Manual creation of
an observable
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();
});
you can also Create an observable from something
// 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
OBSERVING AN OBSERVABLE
observable
subscription
observer
subscription
observer
OBSERVING AN OBSERVABLE
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
Subscribe to an observable
const subscription = source$.subscribe({
x => console.log(x),
err => console.error(err),
() => console.info('done')
});
to unsubscribe from an observable
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);
Define whats to happen on unsubscribe
you should use operators
to compose
new observables
Transforming Observables
Buffer, FlatMap, GroupBy, Map, Scan, Window, ...
Filtering Observables
Debounce, Distinct, Filter, First, Last, Skip, SkipLast, Take ...
Combining Observables
Join, Merge, Switch, Zip, ...
Operators by category
Subjects
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);
Hands-on
Clone this project from github
And PUT SOME MUSIC ON
install rxjs via npm
npm install rxjs
const { Observable } = require('rxjs/Rx');
Observable.of(1,2,3);
Import only what you need
don't forget to import operators
require('rxjs/add/observable/of');
require('rxjs/add/operator/map');
THANK YOU !
You loved the workshop ? give us your feedback
Reactive Programming with RxJS
By Ouadie LAHDIOUI
Reactive Programming with RxJS
- 1,279