SlideShare a Scribd company logo
1 of 77
Download to read offline
RxJS
Reactive extensions for JavaScript
$ whoami
Viliam Elischer
SW Engineer at ZOOM International
twitter.com/vireliam
github.com/vire
Introduction
Theory
Building blocks
Usage
Alternatives
Resources
Agenda
History
Originally project Volta (December 2007)
Erik Meijer: Volta is an experiment that enables Microsoft to explore new ways of
developing distributed applications.
Today ReactiveX supports RxJava, RxJS, Rx.NET, UniRx, RxScala, RxClojure,
RxCpp, Rx.rb, RxPY, RxGroovy, RxJRuby, RxKotlin, RxSwift, RxNetty, RxAndroid
RxCocoa
Mental fathers: Erik Meijer, Matthew Podwysowski
RxJS Contributors: Ben Lesh, Paul Daniels + 164 more individuals
RxJS is set of libraries for
composing asynchronous and event-based
programs.
Developers represent asynchronous data streams
with Observables, query asynchronous data streams
using many operators, and parameterize the
concurrency in the asynchronous data streams using
Schedulers.
Developers represent asynchronous data streams
with Observables, query asynchronous data streams
using many operators, and parameterize the
concurrency in the asynchronous data streams using
Schedulers.
Developers represent asynchronous data streams
with Observables, query asynchronous data streams
using many operators, and parameterize the
concurrency in the asynchronous data streams using
Schedulers.
Asynchronous data streams demystified
A Stream is just a fancy word for
a sequence of “things” streamed over time.
A sequence is infinite until it completes.
It is not possible to add anything after completion.
The act of change on a sequence is simply
an event.
A Stream is an infinite sequence of
events over time.
A Sequence can be observed and acts as
a Subject of observation.
An Observable sequence.
The ability to observe was defined because
there is a good reason or interest.
An Observer is interested in what happens with
the Subject (Observable).
To get notified about changes an Observer must
subscribe to an Observable sequence.
A Subscription represents the contract between
Observer and Observable.
The Subject notifies the Observer about changes
by pushing events.
The Observer represents behavior for handling
events pushed by the observed sequence.
Such prepared reaction to a push happens
asynchronously.
Leveraging Observables from managing the “when”
aspect is possible thanks to Schedulers.
Most important features of Observables are fully
empowered when sophisticated operations are
being performed in form of queries.
Computation scenarios
time / val One value Multiple values
Synchronous | Pull Object Iterables
Array | Map | Set | Object
Asynchronous | Push Promise Observables
Design patterns
Faig Ahmed - Liquid, Handmade Woolen carpet 200x290, year 2014
GOF Design Patterns
Iterator
IEnumerable<T> and IEnumerator<T>
interactive computations where the
consumer synchronously pulls data
from the producer
Observer
IObservable<T> and IObserver<T>
reactive computations where the
producer asynchronously pushes
data to the consumer
http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf
http://josemigueltorres.net/index.php/ienumerableiobservable-duality/
Asynchronously? Sure, we have promises...
Problematic aspects of promises
Error swallow
Bulk processing (map 20 XHRs to 1 result)
Cancellation (context switching)
Replay of previous values
Building blocks
function Disposable() { }
Disposable.prototype.dispose = () => { ... }
function Observable() { }
Observable.prototype.subscribe = observer => { ... }
function Observer() { }
Observer.prototype.onNext = value => { ... };
Observer.prototype.onError = error => { ... };
Observer.prototype.onCompleted = () => { ... };
RxJS = Observables + Operators + Schedulers.
It’s all about operators...
Operator, I need an operator.
We do have operators
131
creation, conversion, combine, functional,
mathematical, time, exceptions, miscellaneous,
selection and primitives
Creation - Observable.just | .return
Rx.Observable.just(42)
.subscribe(val => {console.log('val: ' + val)})
// val: 42
Creation - Observable.create
const source = Rx.Observable.create(observer => {
observer.onNext(42);
observer.onError(new Error('ha-ha!'));
observer.onCompleted();
});
source.subscribe(
val => console.log('onNext:', val),
error => console.log('onError:', error),
() => console.log('onCompleted:')
);
Creation - Observable.create + Disposable
const source = Rx.Observable.create(observer => {
observer.onNext(42);
observer.onError(new Error('ha-ha!'));
observer.onCompleted();
return Rx.Disposable.create(() => console.log('disposed'));
});
source.subscribe(
val => console.log('onNext:', val),
error => console.log('onError:', error),
() => console.log('onCompleted:')
);
Creation - Observable.create + Disposable
const asyncOp = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('resolving!')
resolve(42);
}, 1000);
console.log('promise in progress...')
});
}
asyncOp().then(val => console.log('resolved with: ', val))
Promises can’t be disposed!
const asyncOp = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('resolving!')
resolve(42);
}, 1000);
console.log('promise in progress...')
});
}
asyncOp().then(val => console.log('resolved', val))
const source = Rx.Observable.create(observer => {
console.log('Observable in progress')
const timeout = setTimeout(() => {
observer.onNext('onNext after two seconds!');
}, 2000);
return Rx.Disposable.create(() => {
console.log('disposed');
clearTimeout(timeout);
});
});
const subscription = source.subscribe(
val => console.log('onNext:', val),
);
setTimeout(() => subscription.dispose(), 500);
Creation - Observable.from
Arguments, Array, Iterable, Set, Map, String, Generated sequence
Rx.Observable.from([1, 2, 3], x => x + x).subscribe(
x => console.log(`onNext: ${x}`),
e => console.log(`onError: ${e}`),
() => console.log('onCompleted')
);
// ! 2nd argument is a mapFn
// => onNext: 2
// => onNext: 4
// => onNext: 6
// => onCompleted
Creation - Observable.from${PutHereWhatYouHave}
.fromCallback, .fromPromise, fromEvent, fromNodeCallback,
const firstNameInput = document.querySelector('#firstName');
Rx.Observable.fromEvent(firstNameInput, 'input')
.pluck('target', 'value')
.subscribe(e => console.log(e));
Hot ‘n cold
const source = Rx.Observable.interval(1000)
.map(val => val + 1)
.take(10);
source
.subscribe(val => console.log('first: ' + val));
setTimeout(() => {
source
.subscribe(val => console.log('second: ' + val));
}, 5000);
// "first: 1"
// "first: 2"
// "first: 3"
// "second: 1"
// "first: 4"
// "second: 2"
// ...
const source = Rx.Observable.interval(1000)
.map(val => val + 1)
.take(10)
.publish()
.refCount();
source
.subscribe(val => console.log('first: ' + val));
setTimeout(() => {
source.subscribe(val => console.log('second: ' +
val));
}, 5000);
// "first: 1"
// "first: 2"
// "first: 3"
// "second: 3"
// "first: 4"
// ...
Hot
-
Live stream
.publish() + .refcount()
Cold
-
Recorded video
by default
Query!
.debounce | .throttle
// https://remysharp.com/2010/07/21/throttling-function-calls
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last, deferTimer;
return function () {
var context = scope || this, now = +new Date, args = arguments;
if (last && now < last + threshhold) {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}
window.addEventListener('resize', throttle(function (event)
{console.log('resized');}), false);
Rx.Observable.fromEvent(window, 'resize')
.throttle(250)
.subscribe(val => console.log('resized', window.
innerWidth))
.map and .flatMap
Rx.Observable.fromArray(['good', 'evening', 'ng-
party!'])
.map(item => item.toUpperCase())
.subscribe(val => console.log(val));
// "GOOD"
// "EVENING"
// "NG-PARTY!"
Rx.Observable.fromArray(['good', 'evening', 'ng-
party!'])
.map(item => Promise.resolve(item.toUpperCase()))
.subscribe(val => console.log(val));
// [object Object] { ... }, [object Object] { ... },
[object Object] { ... }
Rx.Observable.fromArray(['good', 'evening', 'ng-party!'])
.flatMap(item => Promise.resolve(item.toUpperCase()))
.subscribe(val => console.log(val));
// "GOOD"
// "EVENING"
// "NG-PARTY!"
.takeUntil
const intervalSource = Rx.Observable.interval(500)
const source = Rx.Observable
.fromEvent(document.querySelector('#toggle-stream'), 'click');
source
.pluck('target', 'checked')
.filter(val => val)
.flatMapLatest(() => intervalSource.takeUntil(source))
.subscribe(val => console.log('isChecked?', val),)
.reduce or .scan
Rx.Observable.fromArray(['It', 'is', 'time', 'for',
'beer','ng-party!'])
.reduce((p, c) => p + ' ' + c, '')
.subscribe(val => console.log(val.trim()));
// "It is time for beer ng-party!"
Rx.Observable.interval(500)
.timeInterval()
.pluck('interval')
.reduce((p, c) => p + c, 10000)
.subscribe(val => console.log(val));
?
?
?
?
?
?
?
?
.reduce or .scan
Rx.Observable.fromArray(['It', 'is', 'time', 'for',
'beer','ng-party!'])
.reduce((p, c) => p + ' ' + c, '')
.subscribe(val => console.log(val.trim()));
// "It is time for beer ng-party!"
Rx.Observable.interval(500)
.timeInterval()
.pluck('interval')
.scan((p, c) => p + c, 10000)
.subscribe(val => console.log(val));
// 10502
// 11001
// 11501
// 12001
Versions
github.com/Reactive-Extensions/RxJS: v4.0.7
github.com/ReactiveX/RxJS: 5.0.0-alpha.14
RxJS Next
npm install rxjs-es
import Rx from 'rxjs/Rx';
Rx.Observable.of(1,2,3)
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
Observable.of(1,2,3).map(x => x + '!!!'); // etc
import {Observable} from 'rxjs/Observable';
import {map} from 'rxjs/operator/map';
Observable.of(1,2,3)::map(x => x + '!!!'); // etc
/* ES7 */
import { map, takeWhile, forEach } from "iterlib";
getPlayers()
::map(x => x.character())
::takeWhile(x => x.strength > 100)
::forEach(x => console.log(x));
/* ES6 */
import { map, takeWhile, forEach } from "iterlib";
let _val;
_val = getPlayers();
_val = map.call(_val, x => x.character());
_val = takeWhile.call(_val, x => x.strength > 100);
_val = forEach.call(_val, x => console.log(x));
Advanced topics
Re-play
Backpressure
Window
ForkJoin
Schedulers
Generators
Rx Testing, Virtual Time,
Marbles
WebSocketsSubject
Use cases
Sane workflows with DOM Events (mousemove, keypress, drag and drop)
UI Manipulation
API Communication
State management (Components, AppState, Dispatching)
Set operations (map, filter, scan)
Transducers
Alternative and affiliates
Bacon, Kefir
Angular 2
github.com/acdlite/redux-rx
garbles/yolk
Resources
xgrommx.github.io/rx-book
rxmarbles.com
egghead.io
gitter.im/Reactive-Extensions/RxJS
Q & A
Thank you
@vireliam
#devsUnited

More Related Content

What's hot

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
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 

What's hot (20)

rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
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 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Add Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJSAdd Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJS
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
JS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless Bebop
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 

Viewers also liked

ReactiveX-SEA
ReactiveX-SEAReactiveX-SEA
ReactiveX-SEA
Yang Yang
 

Viewers also liked (20)

Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScript
 
Reactive Programming and RxJS
Reactive Programming and RxJSReactive Programming and RxJS
Reactive Programming and RxJS
 
Turn Your Designers Into Death Stars with Angular
Turn Your Designers Into Death Stars with AngularTurn Your Designers Into Death Stars with Angular
Turn Your Designers Into Death Stars with Angular
 
Badges? We don't need no stinkin' badges!
Badges? We don't need no stinkin' badges!Badges? We don't need no stinkin' badges!
Badges? We don't need no stinkin' badges!
 
ngAnimate crash course
ngAnimate crash coursengAnimate crash course
ngAnimate crash course
 
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJSngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
 
AngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTMLAngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTML
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and FirebaseGo Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
 
Vývojařská Plzeň - React
Vývojařská Plzeň - ReactVývojařská Plzeň - React
Vývojařská Plzeň - React
 
Ember.js - Jak zatopit a neshořet!
Ember.js - Jak zatopit a neshořet!Ember.js - Jak zatopit a neshořet!
Ember.js - Jak zatopit a neshořet!
 
The REAL Angular Keynote
The REAL Angular KeynoteThe REAL Angular Keynote
The REAL Angular Keynote
 
Keep your side-effects 
in the right place with 
redux observable
Keep your side-effects 
in the right place with 
redux observableKeep your side-effects 
in the right place with 
redux observable
Keep your side-effects 
in the right place with 
redux observable
 
Embrace the Angular 2 Ethos in Angular 1.x
Embrace the Angular 2 Ethos in Angular 1.xEmbrace the Angular 2 Ethos in Angular 1.x
Embrace the Angular 2 Ethos in Angular 1.x
 
FRP with Ractive and RxJS
FRP with Ractive and RxJSFRP with Ractive and RxJS
FRP with Ractive and RxJS
 
ReactiveX-SEA
ReactiveX-SEAReactiveX-SEA
ReactiveX-SEA
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Programação reativa com RxJS e Angular
Programação reativa com RxJS e AngularProgramação reativa com RxJS e Angular
Programação reativa com RxJS e Angular
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Get that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and ElectronGet that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and Electron
 

Similar to RxJS - The Reactive extensions for JavaScript

Similar to RxJS - The Reactive extensions for JavaScript (20)

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 - делаем асинхр...
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Reactive x
Reactive xReactive x
Reactive x
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
The Reactive Landscape
The Reactive LandscapeThe Reactive Landscape
The Reactive Landscape
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-es
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 

Recently uploaded

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 

Recently uploaded (20)

UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 

RxJS - The Reactive extensions for JavaScript

  • 1.
  • 2.
  • 4. $ whoami Viliam Elischer SW Engineer at ZOOM International twitter.com/vireliam github.com/vire
  • 6.
  • 7. History Originally project Volta (December 2007) Erik Meijer: Volta is an experiment that enables Microsoft to explore new ways of developing distributed applications. Today ReactiveX supports RxJava, RxJS, Rx.NET, UniRx, RxScala, RxClojure, RxCpp, Rx.rb, RxPY, RxGroovy, RxJRuby, RxKotlin, RxSwift, RxNetty, RxAndroid RxCocoa Mental fathers: Erik Meijer, Matthew Podwysowski RxJS Contributors: Ben Lesh, Paul Daniels + 164 more individuals
  • 8. RxJS is set of libraries for composing asynchronous and event-based programs.
  • 9. Developers represent asynchronous data streams with Observables, query asynchronous data streams using many operators, and parameterize the concurrency in the asynchronous data streams using Schedulers.
  • 10. Developers represent asynchronous data streams with Observables, query asynchronous data streams using many operators, and parameterize the concurrency in the asynchronous data streams using Schedulers.
  • 11. Developers represent asynchronous data streams with Observables, query asynchronous data streams using many operators, and parameterize the concurrency in the asynchronous data streams using Schedulers.
  • 12.
  • 14. A Stream is just a fancy word for a sequence of “things” streamed over time.
  • 15. A sequence is infinite until it completes. It is not possible to add anything after completion.
  • 16. The act of change on a sequence is simply an event.
  • 17. A Stream is an infinite sequence of events over time.
  • 18. A Sequence can be observed and acts as a Subject of observation.
  • 20.
  • 21. The ability to observe was defined because there is a good reason or interest.
  • 22. An Observer is interested in what happens with the Subject (Observable).
  • 23. To get notified about changes an Observer must subscribe to an Observable sequence.
  • 24. A Subscription represents the contract between Observer and Observable.
  • 25. The Subject notifies the Observer about changes by pushing events.
  • 26. The Observer represents behavior for handling events pushed by the observed sequence.
  • 27. Such prepared reaction to a push happens asynchronously.
  • 28. Leveraging Observables from managing the “when” aspect is possible thanks to Schedulers.
  • 29. Most important features of Observables are fully empowered when sophisticated operations are being performed in form of queries.
  • 30. Computation scenarios time / val One value Multiple values Synchronous | Pull Object Iterables Array | Map | Set | Object Asynchronous | Push Promise Observables
  • 32. Faig Ahmed - Liquid, Handmade Woolen carpet 200x290, year 2014
  • 33. GOF Design Patterns Iterator IEnumerable<T> and IEnumerator<T> interactive computations where the consumer synchronously pulls data from the producer Observer IObservable<T> and IObserver<T> reactive computations where the producer asynchronously pushes data to the consumer http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf http://josemigueltorres.net/index.php/ienumerableiobservable-duality/
  • 34. Asynchronously? Sure, we have promises...
  • 35. Problematic aspects of promises Error swallow Bulk processing (map 20 XHRs to 1 result) Cancellation (context switching) Replay of previous values
  • 36. Building blocks function Disposable() { } Disposable.prototype.dispose = () => { ... } function Observable() { } Observable.prototype.subscribe = observer => { ... } function Observer() { } Observer.prototype.onNext = value => { ... }; Observer.prototype.onError = error => { ... }; Observer.prototype.onCompleted = () => { ... };
  • 37. RxJS = Observables + Operators + Schedulers.
  • 38. It’s all about operators...
  • 39.
  • 40. Operator, I need an operator.
  • 41. We do have operators
  • 42. 131
  • 43. creation, conversion, combine, functional, mathematical, time, exceptions, miscellaneous, selection and primitives
  • 44. Creation - Observable.just | .return Rx.Observable.just(42) .subscribe(val => {console.log('val: ' + val)}) // val: 42
  • 45. Creation - Observable.create const source = Rx.Observable.create(observer => { observer.onNext(42); observer.onError(new Error('ha-ha!')); observer.onCompleted(); }); source.subscribe( val => console.log('onNext:', val), error => console.log('onError:', error), () => console.log('onCompleted:') );
  • 46. Creation - Observable.create + Disposable const source = Rx.Observable.create(observer => { observer.onNext(42); observer.onError(new Error('ha-ha!')); observer.onCompleted(); return Rx.Disposable.create(() => console.log('disposed')); }); source.subscribe( val => console.log('onNext:', val), error => console.log('onError:', error), () => console.log('onCompleted:') );
  • 47. Creation - Observable.create + Disposable const asyncOp = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('resolving!') resolve(42); }, 1000); console.log('promise in progress...') }); } asyncOp().then(val => console.log('resolved with: ', val))
  • 48. Promises can’t be disposed!
  • 49. const asyncOp = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('resolving!') resolve(42); }, 1000); console.log('promise in progress...') }); } asyncOp().then(val => console.log('resolved', val)) const source = Rx.Observable.create(observer => { console.log('Observable in progress') const timeout = setTimeout(() => { observer.onNext('onNext after two seconds!'); }, 2000); return Rx.Disposable.create(() => { console.log('disposed'); clearTimeout(timeout); }); }); const subscription = source.subscribe( val => console.log('onNext:', val), ); setTimeout(() => subscription.dispose(), 500);
  • 50. Creation - Observable.from Arguments, Array, Iterable, Set, Map, String, Generated sequence Rx.Observable.from([1, 2, 3], x => x + x).subscribe( x => console.log(`onNext: ${x}`), e => console.log(`onError: ${e}`), () => console.log('onCompleted') ); // ! 2nd argument is a mapFn // => onNext: 2 // => onNext: 4 // => onNext: 6 // => onCompleted
  • 51. Creation - Observable.from${PutHereWhatYouHave} .fromCallback, .fromPromise, fromEvent, fromNodeCallback, const firstNameInput = document.querySelector('#firstName'); Rx.Observable.fromEvent(firstNameInput, 'input') .pluck('target', 'value') .subscribe(e => console.log(e));
  • 53.
  • 54. const source = Rx.Observable.interval(1000) .map(val => val + 1) .take(10); source .subscribe(val => console.log('first: ' + val)); setTimeout(() => { source .subscribe(val => console.log('second: ' + val)); }, 5000); // "first: 1" // "first: 2" // "first: 3" // "second: 1" // "first: 4" // "second: 2" // ... const source = Rx.Observable.interval(1000) .map(val => val + 1) .take(10) .publish() .refCount(); source .subscribe(val => console.log('first: ' + val)); setTimeout(() => { source.subscribe(val => console.log('second: ' + val)); }, 5000); // "first: 1" // "first: 2" // "first: 3" // "second: 3" // "first: 4" // ...
  • 55. Hot - Live stream .publish() + .refcount() Cold - Recorded video by default
  • 57. .debounce | .throttle // https://remysharp.com/2010/07/21/throttling-function-calls function throttle(fn, threshhold, scope) { threshhold || (threshhold = 250); var last, deferTimer; return function () { var context = scope || this, now = +new Date, args = arguments; if (last && now < last + threshhold) { clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshhold); } else { last = now; fn.apply(context, args); } }; } window.addEventListener('resize', throttle(function (event) {console.log('resized');}), false); Rx.Observable.fromEvent(window, 'resize') .throttle(250) .subscribe(val => console.log('resized', window. innerWidth))
  • 58. .map and .flatMap Rx.Observable.fromArray(['good', 'evening', 'ng- party!']) .map(item => item.toUpperCase()) .subscribe(val => console.log(val)); // "GOOD" // "EVENING" // "NG-PARTY!" Rx.Observable.fromArray(['good', 'evening', 'ng- party!']) .map(item => Promise.resolve(item.toUpperCase())) .subscribe(val => console.log(val)); // [object Object] { ... }, [object Object] { ... }, [object Object] { ... } Rx.Observable.fromArray(['good', 'evening', 'ng-party!']) .flatMap(item => Promise.resolve(item.toUpperCase())) .subscribe(val => console.log(val)); // "GOOD" // "EVENING" // "NG-PARTY!"
  • 59.
  • 60. .takeUntil const intervalSource = Rx.Observable.interval(500) const source = Rx.Observable .fromEvent(document.querySelector('#toggle-stream'), 'click'); source .pluck('target', 'checked') .filter(val => val) .flatMapLatest(() => intervalSource.takeUntil(source)) .subscribe(val => console.log('isChecked?', val),)
  • 61. .reduce or .scan Rx.Observable.fromArray(['It', 'is', 'time', 'for', 'beer','ng-party!']) .reduce((p, c) => p + ' ' + c, '') .subscribe(val => console.log(val.trim())); // "It is time for beer ng-party!" Rx.Observable.interval(500) .timeInterval() .pluck('interval') .reduce((p, c) => p + c, 10000) .subscribe(val => console.log(val)); ? ? ? ? ? ? ? ?
  • 62.
  • 63. .reduce or .scan Rx.Observable.fromArray(['It', 'is', 'time', 'for', 'beer','ng-party!']) .reduce((p, c) => p + ' ' + c, '') .subscribe(val => console.log(val.trim())); // "It is time for beer ng-party!" Rx.Observable.interval(500) .timeInterval() .pluck('interval') .scan((p, c) => p + c, 10000) .subscribe(val => console.log(val)); // 10502 // 11001 // 11501 // 12001
  • 66. RxJS Next npm install rxjs-es import Rx from 'rxjs/Rx'; Rx.Observable.of(1,2,3) import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; Observable.of(1,2,3).map(x => x + '!!!'); // etc import {Observable} from 'rxjs/Observable'; import {map} from 'rxjs/operator/map'; Observable.of(1,2,3)::map(x => x + '!!!'); // etc /* ES7 */ import { map, takeWhile, forEach } from "iterlib"; getPlayers() ::map(x => x.character()) ::takeWhile(x => x.strength > 100) ::forEach(x => console.log(x)); /* ES6 */ import { map, takeWhile, forEach } from "iterlib"; let _val; _val = getPlayers(); _val = map.call(_val, x => x.character()); _val = takeWhile.call(_val, x => x.strength > 100); _val = forEach.call(_val, x => console.log(x));
  • 68. Use cases Sane workflows with DOM Events (mousemove, keypress, drag and drop) UI Manipulation API Communication State management (Components, AppState, Dispatching) Set operations (map, filter, scan) Transducers
  • 76. Q & A