SlideShare a Scribd company logo
1 of 28
Download to read offline
RxJS - What is it?
 
Adam Gołąb
Fullstack JS Developer @ Brainhub
Reactive Programming
Reactive programming is an asynchronous programming
paradigm concerned with data streams and the
propagation of change.
 
Think of RxJS as Lodash for events.
 
Developed by Microsoft, in collaboration with a community
of open source developers.
RxJS is a library for composing asynchronous and event-
based programs by using observable sequences. It
provides one core type, the Observable, satellite types
(Observer, Schedulers, Subjects) and operators
inspired by Array#extras (map, filter, reduce,
every, etc) to allow handling asynchronous events as
collections.
Observer
class Observable {
notify() {
for observer in this.observers {
observer.notifyAboutNewState();
}
}
}
Real world example!
Vanilla JS
const button = document.querySelector('button');
button.addEventListener('click', () => console.log('Clicked!'))
RxJS
const button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click')
.subscribe(() => console.log('Clicked!'));
Purity!
Vanilla JS
let count = 0;
const button = document.querySelector('button');
button.addEventListener('click', () =>
console.log(`Clicked ${++count} times`)
);
RxJS
const button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click')
.scan(count => count + 1, 0)
.subscribe(count => console.log(`Clicked ${count} times`));
Observable
Lazy Push collections of multiple values. They ll the
missing spot in the following table:
  Single Multiple
Pull Function Iterator
Push Promise Observable
Observable
"just before subscribe"
"got value 1"
"got value 2"
"got value 3"
"just after subscribe"
"got value 4"
"done"
❯
var observable = Rx.Observable.create(
function (observer) {
observer.next(1);
observer.next(2);
observer.next(3);
setTimeout(() => {
observer.next(4);
observer.complete();
}, 1000);
}
);
console.log('just before subscribe');
observable.subscribe({
next: x => console.log('got value ' + x),
error: err => console.error(
'something wrong occurred: ' + err
),
complete: () => console.log('done'),
});
console.log('just after subscribe');
Run ClearConsoleJavaScript ▾
HTML CSS JavaScript Console Output HelpJS Bin Save
Executing Observables
The code inside Observable.create(function
subscribe(observer) {...}) represents an
"Observable execution", a lazy computation that only
happens for each Observer that subscribes. The execution
produces multiple values over time, either synchronously or
asynchronously.
 
 
 
Types of values.
There are three types of values an Observable Execution
can deliver:
"Next" noti cation: sends a value such as a Number, a
String, an Object, etc.
"Error" noti cation: sends a JavaScript Error or exception.
"Complete" noti cation: does not send a value.
Executing Observables
"got value 1"
"got value 2"
"got value 3"
"done"
❯
const observable = Rx.Observable.create(
function subscribe(observer) {
try {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete();
observer.next(4);
} catch (err) {
observer.error(err);
}
}
);
observable.subscribe({
next: x => console.log('got value ' + x),
error: err => console.error(
'something wrong occurred: ' + err
),
complete: () => console.log('done'),
});
Run ClearConsoleJavaScript ▾
HTML CSS JavaScript Console Output HelpJS Bin Save
Subject
A Subject is like an Observable, but can multicast to
many Observers.
Subjects are like EventEmitters they maintain a
registry of many listeners
Subject
"observerA: 1"
"observerB: 1"
"observerA: 2"
"observerB: 2"
❯
const subject = new Rx.Subject();
subject.subscribe({
next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
next: (v) => console.log('observerB: ' + v)
});
subject.next(1);
subject.next(2);
Run ClearConsoleJavaScript ▾
HTML CSS JavaScript Console Output HelpJS Bin Save
Behavior Subject
One of the variants of Subjects is the
BehaviorSubject, which has a notion of "the current
value". It stores the latest value emitted to its consumers,
and whenever a new Observer subscribes, it will
immediately receive the "current value" from the
BehaviorSubject.
Bahavior Subject
"observerA: 0"
"observerA: 1"
"observerA: 2"
"observerB: 2"
"observerA: 3"
"observerB: 3"
❯
const subject = new Rx.BehaviorSubject(0);
// 0 is the initial value
subject.subscribe({
next: (v) => console.log('observerA: ' + v)
});
subject.next(1);
subject.next(2);
subject.subscribe({
next: (v) => console.log('observerB: ' + v)
});
subject.next(3);
Run ClearConsoleJavaScript ▾
HTML CSS JavaScript Console Output HelpJS Bin Save
Replay Subject
A ReplaySubject is similar to a BehaviorSubject in
that it can send old values to new subscribers, but it can
also record a part of the Observable execution.
Replay Subject
"observerA: 1"
"observerA: 2"
"observerA: 3"
"observerA: 4"
"observerB: 2"
"observerB: 3"
"observerB: 4"
"observerA: 5"
"observerB: 5"
❯
const subject = new Rx.ReplaySubject(3);
// buffer 3 values for new subscribers
subject.subscribe({
next: (v) => console.log('observerA: ' + v)
});
subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);
subject.subscribe({
next: (v) => console.log('observerB: ' + v)
});
subject.next(5);
Run ClearConsoleJavaScript ▾
HTML CSS JavaScript Console Output HelpJS Bin Save
What are operators?
Operators are methods on the Observable type, such
as .map(...), .filter(...), .merge(...), etc.
When called, they do not change the existing Observable
instance. Instead, they return a new Observable, whose
subscription logic is based on the rst Observable.
Operators
10
20
30
40
❯
function multiplyByTen(input) {
const output = Rx.Observable.create(
function subscribe(observer) {
input.subscribe({
next: (v) => observer.next(10 * v),
error: (err) => observer.error(err),
complete: () => observer.complete()
});
}
);
return output;
}
const input = Rx.Observable.from([1, 2, 3, 4]);
const output = multiplyByTen(input);
output.subscribe(x => console.log(x));
Run ClearConsoleJavaScript ▾
HTML CSS JavaScript Console Output HelpJS Bin Save
Types of Operators
Creation
Transformation
Filtering
Combination
Multicasting
Error Handling
Utility
Operators example
"typed char 1 of
type numeric"
"typed char a of
type alpha"
"typed char @ of
type special"
"typed char Enter
of type special"
❯
const input = document.querySelector('input');
const typedChars = Rx.Observable.fromEvent(input, 'keypress');
const alphaChars = typedChars
.filter(event => /^[A-z]$/.test(event.key))
.map(event => ({ type: 'alpha', value: event.key }));
const numericChars = typedChars
.filter(event => /^d$/.test(event.key))
.map(event => ({ type: 'numeric', value: event.key }));
const specialChars = typedChars
.filter(event => /W|w{2,}/.test(event.key))
.map(event => ({ type: 'special', value: event.key }));
const charsToLog = alphaChars
.merge(numericChars)
.merge(specialChars);
charsToLog.subscribe(key =>
console.log(`typed char ${key.value} of type ${key.type}`)
);
ClearConsoleJavaScript ▾ 1a@
Run with JS
Auto-run JS
HTML CSS JavaScript Console Output HelpJS Bin Save
Useful Resources
http://reactivex.io/rxjs/
http://rxmarbles.com/
http://jaredforsyth.com/rxvision/
Questions?

More Related Content

What's hot

What's hot (20)

Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
 
RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)
 
RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
angular fundamentals.pdf
angular fundamentals.pdfangular fundamentals.pdf
angular fundamentals.pdf
 
React Hooks
React HooksReact Hooks
React Hooks
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 

Similar to Introduction to RxJS

rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
Alexander Mostovenko
 

Similar to Introduction to RxJS (20)

Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java script
 
From zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptFrom zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScript
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
 
Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJS
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
Intro to Rx Java
Intro to Rx JavaIntro to Rx Java
Intro to Rx Java
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Reactive x
Reactive xReactive x
Reactive x
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
 
Streams
StreamsStreams
Streams
 

More from Brainhub

More from Brainhub (20)

AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?
 
Konfiguracja GitLab CI/CD pipelines od podstaw
Konfiguracja GitLab CI/CD pipelines od podstawKonfiguracja GitLab CI/CD pipelines od podstaw
Konfiguracja GitLab CI/CD pipelines od podstaw
 
tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?
 
Solid.js - następca Reacta?
Solid.js - następca Reacta?Solid.js - następca Reacta?
Solid.js - następca Reacta?
 
Struktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcieStruktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcie
 
WebAssembly - czy dzisiaj mi się to przyda do pracy?
WebAssembly - czy dzisiaj mi się to przyda do pracy?WebAssembly - czy dzisiaj mi się to przyda do pracy?
WebAssembly - czy dzisiaj mi się to przyda do pracy?
 
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
 
Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!
 
How I taught the messenger to tell lame jokes
How I taught the messenger to tell lame jokesHow I taught the messenger to tell lame jokes
How I taught the messenger to tell lame jokes
 
The hunt of the unicorn, to capture productivity
The hunt of the unicorn, to capture productivityThe hunt of the unicorn, to capture productivity
The hunt of the unicorn, to capture productivity
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
 
WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?
 
React performance
React performanceReact performance
React performance
 
React Native in a nutshell
React Native in a nutshellReact Native in a nutshell
React Native in a nutshell
 
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
 
Technologia, a Startup - Brainhub
Technologia, a Startup - BrainhubTechnologia, a Startup - Brainhub
Technologia, a Startup - Brainhub
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
How should you React to Redux
How should you React to ReduxHow should you React to Redux
How should you React to Redux
 
Wprowadzenie do React
Wprowadzenie do ReactWprowadzenie do React
Wprowadzenie do React
 
JavaScript and Desktop Apps - Introduction to Electron
JavaScript and Desktop Apps - Introduction to ElectronJavaScript and Desktop Apps - Introduction to Electron
JavaScript and Desktop Apps - Introduction to Electron
 

Recently uploaded

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
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
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 ...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
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 🔝✔️✔️
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
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
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
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
 
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
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
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
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%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
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 

Introduction to RxJS

  • 1. RxJS - What is it?
  • 2.   Adam Gołąb Fullstack JS Developer @ Brainhub
  • 3. Reactive Programming Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change.
  • 4.   Think of RxJS as Lodash for events.  
  • 5. Developed by Microsoft, in collaboration with a community of open source developers. RxJS is a library for composing asynchronous and event- based programs by using observable sequences. It provides one core type, the Observable, satellite types (Observer, Schedulers, Subjects) and operators inspired by Array#extras (map, filter, reduce, every, etc) to allow handling asynchronous events as collections.
  • 6.
  • 7. Observer class Observable { notify() { for observer in this.observers { observer.notifyAboutNewState(); } } }
  • 8. Real world example! Vanilla JS const button = document.querySelector('button'); button.addEventListener('click', () => console.log('Clicked!')) RxJS const button = document.querySelector('button'); Rx.Observable.fromEvent(button, 'click') .subscribe(() => console.log('Clicked!'));
  • 9. Purity! Vanilla JS let count = 0; const button = document.querySelector('button'); button.addEventListener('click', () => console.log(`Clicked ${++count} times`) ); RxJS const button = document.querySelector('button'); Rx.Observable.fromEvent(button, 'click') .scan(count => count + 1, 0) .subscribe(count => console.log(`Clicked ${count} times`));
  • 10.
  • 11. Observable Lazy Push collections of multiple values. They ll the missing spot in the following table:   Single Multiple Pull Function Iterator Push Promise Observable
  • 12. Observable "just before subscribe" "got value 1" "got value 2" "got value 3" "just after subscribe" "got value 4" "done" ❯ var observable = Rx.Observable.create( function (observer) { observer.next(1); observer.next(2); observer.next(3); setTimeout(() => { observer.next(4); observer.complete(); }, 1000); } ); console.log('just before subscribe'); observable.subscribe({ next: x => console.log('got value ' + x), error: err => console.error( 'something wrong occurred: ' + err ), complete: () => console.log('done'), }); console.log('just after subscribe'); Run ClearConsoleJavaScript ▾ HTML CSS JavaScript Console Output HelpJS Bin Save
  • 13. Executing Observables The code inside Observable.create(function subscribe(observer) {...}) represents an "Observable execution", a lazy computation that only happens for each Observer that subscribes. The execution produces multiple values over time, either synchronously or asynchronously.      
  • 14. Types of values. There are three types of values an Observable Execution can deliver: "Next" noti cation: sends a value such as a Number, a String, an Object, etc. "Error" noti cation: sends a JavaScript Error or exception. "Complete" noti cation: does not send a value.
  • 15. Executing Observables "got value 1" "got value 2" "got value 3" "done" ❯ const observable = Rx.Observable.create( function subscribe(observer) { try { observer.next(1); observer.next(2); observer.next(3); observer.complete(); observer.next(4); } catch (err) { observer.error(err); } } ); observable.subscribe({ next: x => console.log('got value ' + x), error: err => console.error( 'something wrong occurred: ' + err ), complete: () => console.log('done'), }); Run ClearConsoleJavaScript ▾ HTML CSS JavaScript Console Output HelpJS Bin Save
  • 16. Subject A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters they maintain a registry of many listeners
  • 17. Subject "observerA: 1" "observerB: 1" "observerA: 2" "observerB: 2" ❯ const subject = new Rx.Subject(); subject.subscribe({ next: (v) => console.log('observerA: ' + v) }); subject.subscribe({ next: (v) => console.log('observerB: ' + v) }); subject.next(1); subject.next(2); Run ClearConsoleJavaScript ▾ HTML CSS JavaScript Console Output HelpJS Bin Save
  • 18. Behavior Subject One of the variants of Subjects is the BehaviorSubject, which has a notion of "the current value". It stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the "current value" from the BehaviorSubject.
  • 19. Bahavior Subject "observerA: 0" "observerA: 1" "observerA: 2" "observerB: 2" "observerA: 3" "observerB: 3" ❯ const subject = new Rx.BehaviorSubject(0); // 0 is the initial value subject.subscribe({ next: (v) => console.log('observerA: ' + v) }); subject.next(1); subject.next(2); subject.subscribe({ next: (v) => console.log('observerB: ' + v) }); subject.next(3); Run ClearConsoleJavaScript ▾ HTML CSS JavaScript Console Output HelpJS Bin Save
  • 20. Replay Subject A ReplaySubject is similar to a BehaviorSubject in that it can send old values to new subscribers, but it can also record a part of the Observable execution.
  • 21. Replay Subject "observerA: 1" "observerA: 2" "observerA: 3" "observerA: 4" "observerB: 2" "observerB: 3" "observerB: 4" "observerA: 5" "observerB: 5" ❯ const subject = new Rx.ReplaySubject(3); // buffer 3 values for new subscribers subject.subscribe({ next: (v) => console.log('observerA: ' + v) }); subject.next(1); subject.next(2); subject.next(3); subject.next(4); subject.subscribe({ next: (v) => console.log('observerB: ' + v) }); subject.next(5); Run ClearConsoleJavaScript ▾ HTML CSS JavaScript Console Output HelpJS Bin Save
  • 22.
  • 23. What are operators? Operators are methods on the Observable type, such as .map(...), .filter(...), .merge(...), etc. When called, they do not change the existing Observable instance. Instead, they return a new Observable, whose subscription logic is based on the rst Observable.
  • 24. Operators 10 20 30 40 ❯ function multiplyByTen(input) { const output = Rx.Observable.create( function subscribe(observer) { input.subscribe({ next: (v) => observer.next(10 * v), error: (err) => observer.error(err), complete: () => observer.complete() }); } ); return output; } const input = Rx.Observable.from([1, 2, 3, 4]); const output = multiplyByTen(input); output.subscribe(x => console.log(x)); Run ClearConsoleJavaScript ▾ HTML CSS JavaScript Console Output HelpJS Bin Save
  • 26. Operators example "typed char 1 of type numeric" "typed char a of type alpha" "typed char @ of type special" "typed char Enter of type special" ❯ const input = document.querySelector('input'); const typedChars = Rx.Observable.fromEvent(input, 'keypress'); const alphaChars = typedChars .filter(event => /^[A-z]$/.test(event.key)) .map(event => ({ type: 'alpha', value: event.key })); const numericChars = typedChars .filter(event => /^d$/.test(event.key)) .map(event => ({ type: 'numeric', value: event.key })); const specialChars = typedChars .filter(event => /W|w{2,}/.test(event.key)) .map(event => ({ type: 'special', value: event.key })); const charsToLog = alphaChars .merge(numericChars) .merge(specialChars); charsToLog.subscribe(key => console.log(`typed char ${key.value} of type ${key.type}`) ); ClearConsoleJavaScript ▾ 1a@ Run with JS Auto-run JS HTML CSS JavaScript Console Output HelpJS Bin Save