SlideShare una empresa de Scribd logo
1 de 28
Descargar para leer sin conexión
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?

Más contenido relacionado

La actualidad más candente

RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019Fabio Biondi
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"Fabio Biondi
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data BindingDuy Khanh
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 

La actualidad más candente (20)

RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019RxJS & Angular Reactive Forms @ Codemotion 2019
RxJS & Angular Reactive Forms @ Codemotion 2019
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"Introduction for Master Class "Amazing Reactive Forms"
Introduction for Master Class "Amazing Reactive Forms"
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Rust
RustRust
Rust
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React Context API
React Context APIReact Context API
React Context API
 
Angular
AngularAngular
Angular
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Angular
AngularAngular
Angular
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 

Similar a Introduction to RxJS

Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio
 
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 scriptMaurice De Beijer [MVP]
 
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 JavaScriptMaurice De Beijer [MVP]
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
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 - делаем асинхр...GeeksLab Odessa
 
Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJSRavi Mone
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptViliam Elischer
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript BootcampAndreCharland
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGDG Korea
 

Similar a 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
 

Más de Brainhub

AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?Brainhub
 
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 podstawBrainhub
 
tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?Brainhub
 
Solid.js - następca Reacta?
Solid.js - następca Reacta?Solid.js - następca Reacta?
Solid.js - następca Reacta?Brainhub
 
Struktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcieStruktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcieBrainhub
 
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?Brainhub
 
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!Brainhub
 
Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!Brainhub
 
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 jokesBrainhub
 
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 productivityBrainhub
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wildBrainhub
 
WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?Brainhub
 
React performance
React performanceReact performance
React performanceBrainhub
 
React Native in a nutshell
React Native in a nutshellReact Native in a nutshell
React Native in a nutshellBrainhub
 
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)Brainhub
 
Technologia, a Startup - Brainhub
Technologia, a Startup - BrainhubTechnologia, a Startup - Brainhub
Technologia, a Startup - BrainhubBrainhub
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLBrainhub
 
How should you React to Redux
How should you React to ReduxHow should you React to Redux
How should you React to ReduxBrainhub
 
Wprowadzenie do React
Wprowadzenie do ReactWprowadzenie do React
Wprowadzenie do ReactBrainhub
 
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 ElectronBrainhub
 

Más de 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
 

Último

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
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 GoalsJhone kinadey
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
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...panagenda
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
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...ICS
 
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 ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Último (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.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
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
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...
 
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
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

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