SlideShare ist ein Scribd-Unternehmen logo
1 von 21
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Reactive computing
Reactive computingReactive computing
Reactive computing
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoa
 
The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
C# console programms
C# console programmsC# console programms
C# console programms
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
ReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IIReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of II
 
Lex programming
Lex programmingLex programming
Lex programming
 
Pattern printing programs
Pattern printing programsPattern printing programs
Pattern printing programs
 
DSU C&C++ Practical File Diploma
DSU C&C++ Practical File DiplomaDSU C&C++ Practical File Diploma
DSU C&C++ Practical File Diploma
 
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn TớiTech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
Tech Talk #4 : RxJava and Using RxJava in MVP - Dương Văn Tới
 
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapperSF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
 
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
A "Do-It-Yourself" Specification Language with BeepBeep 3 (Talk @ Dagstuhl 2017)
 
Lab 1
Lab 1Lab 1
Lab 1
 
Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoa
 
C#
C#C#
C#
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 

Ähnlich wie Rx – reactive extensions

Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUI
kiahiska
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 

Ähnlich wie Rx – reactive extensions (20)

Reactive x
Reactive xReactive x
Reactive x
 
Reacting with ReactiveUI
Reacting with ReactiveUIReacting with ReactiveUI
Reacting with ReactiveUI
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensions
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Kürzlich hochgeladen (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

Rx – reactive extensions

  • 1. RX – Reactive Extensions
  • 2. 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
  • 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 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
  • 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 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
  • 14. 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();
  • 15. Subject  An observable that allows values to be sent to many observers.  Unlike observable, no multiple observable execution occurs  Maintains registry of observers
  • 16. 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();
  • 17. BehaviorSubject  Same as Subject  Contains notion of “current value”  All observers will first receive the current value immediately  Useful for representing "values over time"
  • 18. 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
  • 19. Rx operators  Operator categories:  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