KEMBAR78
Rx – reactive extensions | PPTX
RX – Reactive Extensions
Observer pattern
 Software design
 Subject maintains list of Dependents or Observers
 Observer registers for future notification
 Subject notifies observer of state change
 Decoupling components
 Event driven software
What is RX
 is a set of types representing asynchronous data streams
 a set of operators over asynchronous data streams
 a set of types to parameterize concurrencyRxJS
 RxJS = Observables + LINQ + Schedulers
 ReactiveX combines the Observer pattern with the Iterator
pattern and functional programming with collections to fill the need for an
ideal way of managing sequences of events.

What is Rx
 Observable: represents the idea of an invokable collection of future values or
events.
 Observer: is a collection of callbacks that knows how to listen to values delivered
by the Observable.
 Subscription: represents the execution of an Observable, is primarily useful for
cancelling the execution.
 Operators: are pure functions that enable a functional programming style of
dealing with collections with operations like map, filter, concat, flatMap, etc.
 Subject: is the equivalent to an EventEmitter, and the only way of multicasting a
value or event to multiple Observers.
 Schedulers: are centralized dispatchers to control concurrency, allowing us to
coordinate when computation happens on e.g. setTimeout or
requestAnimationFrame
Essentials
interface Observer {
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}
interface Observable<T> {
subscribe(next: (value: T) => void, error: (err: any) => void, complete: () => void): Subscription;
}
Observables as generalizations of functions
function foo() {
console.log('Hello');
return 42;
}
var x = foo.call(); // same as foo()
console.log(x);
var y = foo.call(); // same as foo()
console.log(y);
Output:
"Hello"
42
"Hello"
42
var foo = Rx.Observable.create(function (observer) {
console.log('Hello');
observer.next(42);
});
foo.subscribe(function (x) {
console.log(x);
});
foo.subscribe(function (y) {
console.log(y);
});
Output:
"Hello"
42
"Hello"
42
 Observables are like functions with zero arguments, but generalize those to
allow multiple values
Observables as generalizations of functions
Creating Observables
var foo = Rx.Observable.create(function subscribe(observer) {
console.log('Hello');
observer.next(42);
observer.next(100); // "return" another value
observer.next(200); // "return" yet another
setTimeout(() => {
observer.next(300); // happens asynchronously
}, 1000);
});
console.log('before');
foo.subscribe(function (x) {
console.log(x);
});
console.log('after');
Output:
"before"
"Hello"
42
100
200
"after“
300
Subscribing to observable
 myObservable.subscribe((x) => console.log(x))
 Each subscribe triggers the subscribe function provided when creating the
Observable (Observable.create(function subscribe(observer) {...}))
 Providing callback on which data will be delivered
Observable execution
var foo = Rx.Observable.create(function subscribe(observer) {
// code here is run once for each observer when he subscribes
observer.next(42);
observer.next(100);
observer.next(200);
});
foo.subscribe(function (x) {
console.log(x);
});
• Multiple subscriptions, multiple executions.
• No execution context sharing
• Each execution can produce multiple values, synchronously or
asynchronously
Observable execution
Three types of return values from Observable execution:
 "Next" notification: sends a value such as a Number, a String, an Object, etc.
 "Error" notification: sends a JavaScript Error or exception.
 "Complete" notification: does not send a value.
 Infinite next notifications
 Once Error or Complete is delivered, nothing else is delivered afterwards
Observable execution
Observable execution
Subscription and disposing Observable
execution
 Execution can run infinitely. We
need to stop it
 Subscription is object representing
disposable resources
 Unsubscribe method stops
execution and dispose resource
let foo = Rx.Observable.create(function
subscribe(observer) {
let intervalId = setInterval(() => {
observer.next(100);
}, 1000);
return function unsubscribe() {
clearInterval(intervalId);
};
});
let subscription = foo.subscribe((x) => console.log(x));
subscription.unsubscribe();
Subject
 An observable that allows values to be sent to many observers.
 Unlike observable, no multiple observable execution occurs
 Maintains registry of observers
Subject
 Is observable:
var subject = new Rx.Subject();
subject.subscribe({
next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
next: (v) => console.log('observerB: ' + v)
});
 Is observer:
subject.next(100);
subject.next(200);
subject.complete();
BehaviorSubject
 Same as Subject
 Contains notion of “current value”
 All observers will first receive the current value immediately
 Useful for representing "values over time"
Rx operators
 Provide the usability behind the foundation that is the observable
 Provide means for composing complex asynchronous code
 Methods on the Observable type: .map(…).filter(…).merge(…)
 DO NOT modify the existing observable, but return a NEW Observable
Rx operators
 Operator categories:
 Creation
 Transformation
 Filtering
 Combination
 Multicasting
 Utility
 Conditional
 Mathematical and aggregation
Rx operators
Creation
 create
 empty
 from
 fromEvent
 fromPromise
 of
 throw
 timer
Transformation
 map
 mapTo
 mergeMap
 pluck
 switchMap
Filtering
 debounceTime
 distinctUntilCh
anged
 filter
 skip
 take
Combination
 combineLatest
 concat
 forkJoin
 merge
 switch
Creation
 do
 delay
 toPromise
References
 https://en.wikipedia.org/wiki/Observer_pattern
 https://yobriefca.se/presentations/tyrannosaurus-rx.pdf
 http://reactivex.io/rxjs/manual/overview.html
 https://www.slideshare.net/mattpodwysocki/cascadiajs-dont-cross-the-
streams
 Playground: https://rxviz.com/examples/random-error

Rx – reactive extensions

  • 1.
    RX – ReactiveExtensions
  • 2.
    Observer pattern  Softwaredesign  Subject maintains list of Dependents or Observers  Observer registers for future notification  Subject notifies observer of state change  Decoupling components  Event driven software
  • 3.
    What is RX is a set of types representing asynchronous data streams  a set of operators over asynchronous data streams  a set of types to parameterize concurrencyRxJS  RxJS = Observables + LINQ + Schedulers  ReactiveX combines the Observer pattern with the Iterator pattern and functional programming with collections to fill the need for an ideal way of managing sequences of events. 
  • 4.
    What is Rx Observable: represents the idea of an invokable collection of future values or events.  Observer: is a collection of callbacks that knows how to listen to values delivered by the Observable.  Subscription: represents the execution of an Observable, is primarily useful for cancelling the execution.  Operators: are pure functions that enable a functional programming style of dealing with collections with operations like map, filter, concat, flatMap, etc.  Subject: is the equivalent to an EventEmitter, and the only way of multicasting a value or event to multiple Observers.  Schedulers: are centralized dispatchers to control concurrency, allowing us to coordinate when computation happens on e.g. setTimeout or requestAnimationFrame
  • 5.
    Essentials interface Observer { next:(value: T) => void; error: (err: any) => void; complete: () => void; } interface Observable<T> { subscribe(next: (value: T) => void, error: (err: any) => void, complete: () => void): Subscription; }
  • 6.
    Observables as generalizationsof functions function foo() { console.log('Hello'); return 42; } var x = foo.call(); // same as foo() console.log(x); var y = foo.call(); // same as foo() console.log(y); Output: "Hello" 42 "Hello" 42
  • 7.
    var foo =Rx.Observable.create(function (observer) { console.log('Hello'); observer.next(42); }); foo.subscribe(function (x) { console.log(x); }); foo.subscribe(function (y) { console.log(y); }); Output: "Hello" 42 "Hello" 42  Observables are like functions with zero arguments, but generalize those to allow multiple values Observables as generalizations of functions
  • 8.
    Creating Observables var foo= Rx.Observable.create(function subscribe(observer) { console.log('Hello'); observer.next(42); observer.next(100); // "return" another value observer.next(200); // "return" yet another setTimeout(() => { observer.next(300); // happens asynchronously }, 1000); }); console.log('before'); foo.subscribe(function (x) { console.log(x); }); console.log('after'); Output: "before" "Hello" 42 100 200 "after“ 300
  • 9.
    Subscribing to observable myObservable.subscribe((x) => console.log(x))  Each subscribe triggers the subscribe function provided when creating the Observable (Observable.create(function subscribe(observer) {...}))  Providing callback on which data will be delivered
  • 10.
    Observable execution var foo= Rx.Observable.create(function subscribe(observer) { // code here is run once for each observer when he subscribes observer.next(42); observer.next(100); observer.next(200); }); foo.subscribe(function (x) { console.log(x); }); • Multiple subscriptions, multiple executions. • No execution context sharing • Each execution can produce multiple values, synchronously or asynchronously
  • 11.
    Observable execution Three typesof return values from Observable execution:  "Next" notification: sends a value such as a Number, a String, an Object, etc.  "Error" notification: sends a JavaScript Error or exception.  "Complete" notification: does not send a value.  Infinite next notifications  Once Error or Complete is delivered, nothing else is delivered afterwards
  • 12.
  • 13.
  • 14.
    Subscription and disposingObservable execution  Execution can run infinitely. We need to stop it  Subscription is object representing disposable resources  Unsubscribe method stops execution and dispose resource let foo = Rx.Observable.create(function subscribe(observer) { let intervalId = setInterval(() => { observer.next(100); }, 1000); return function unsubscribe() { clearInterval(intervalId); }; }); let subscription = foo.subscribe((x) => console.log(x)); subscription.unsubscribe();
  • 15.
    Subject  An observablethat allows values to be sent to many observers.  Unlike observable, no multiple observable execution occurs  Maintains registry of observers
  • 16.
    Subject  Is observable: varsubject = new Rx.Subject(); subject.subscribe({ next: (v) => console.log('observerA: ' + v) }); subject.subscribe({ next: (v) => console.log('observerB: ' + v) });  Is observer: subject.next(100); subject.next(200); subject.complete();
  • 17.
    BehaviorSubject  Same asSubject  Contains notion of “current value”  All observers will first receive the current value immediately  Useful for representing "values over time"
  • 18.
    Rx operators  Providethe usability behind the foundation that is the observable  Provide means for composing complex asynchronous code  Methods on the Observable type: .map(…).filter(…).merge(…)  DO NOT modify the existing observable, but return a NEW Observable
  • 19.
    Rx operators  Operatorcategories:  Creation  Transformation  Filtering  Combination  Multicasting  Utility  Conditional  Mathematical and aggregation
  • 20.
    Rx operators Creation  create empty  from  fromEvent  fromPromise  of  throw  timer Transformation  map  mapTo  mergeMap  pluck  switchMap Filtering  debounceTime  distinctUntilCh anged  filter  skip  take Combination  combineLatest  concat  forkJoin  merge  switch Creation  do  delay  toPromise
  • 21.
    References  https://en.wikipedia.org/wiki/Observer_pattern  https://yobriefca.se/presentations/tyrannosaurus-rx.pdf http://reactivex.io/rxjs/manual/overview.html  https://www.slideshare.net/mattpodwysocki/cascadiajs-dont-cross-the- streams  Playground: https://rxviz.com/examples/random-error