SlideShare a Scribd company logo
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

Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
Christoffer Noring
 
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)
Tracy Lee
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
Tracy Lee
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
Tracy Lee
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
Apigee | Google Cloud
 
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
WebStackAcademy
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
Derek Willian Stavis
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
Valeri Karpov
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
React Context API
React Context APIReact Context API
React Context API
NodeXperts
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
Express js
Express jsExpress js
Express js
Manav Prasad
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
NexThoughts Technologies
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
Eman Mohamed
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
React Hooks
React HooksReact Hooks
React Hooks
Erez Cohen
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
felixbillon
 

What's hot (20)

Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
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 Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
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
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
React Context API
React Context APIReact Context API
React Context API
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Express js
Express jsExpress js
Express js
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
React Hooks
React HooksReact Hooks
React Hooks
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 

Similar to Introduction to RxJS

Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
Luis 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 script
Maurice 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 JavaScript
Maurice De Beijer [MVP]
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
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
 
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
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
Voislav Mishevski
 
Reactive programming and RxJS
Reactive programming and RxJSReactive programming and RxJS
Reactive programming and RxJS
Ravi Mone
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
Alexander Mostovenko
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
Pratama Nur Wijaya
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
AndreCharland
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
Intro to Rx Java
Intro to Rx JavaIntro to Rx Java
Intro to Rx Java
Syed Awais Mazhar Bukhari
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
Christoffer Noring
 
Reactive x
Reactive xReactive x
Reactive x
Gabriel Araujo
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
Rick Warren
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
GDG Korea
 
Streams
StreamsStreams

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

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 podstaw
Brainhub
 
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 JavaScripcie
Brainhub
 
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 jokes
Brainhub
 
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
Brainhub
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
Brainhub
 
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 performance
Brainhub
 
React Native in a nutshell
React Native in a nutshellReact Native in a nutshell
React Native in a nutshell
Brainhub
 
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 - Brainhub
Brainhub
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Brainhub
 
How should you React to Redux
How should you React to ReduxHow should you React to Redux
How should you React to Redux
Brainhub
 
Wprowadzenie do React
Wprowadzenie do ReactWprowadzenie do React
Wprowadzenie do React
Brainhub
 
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
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

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 

Recently uploaded (20)

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 

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