SlideShare a Scribd company logo
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
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
RxJS - The Reactive extensions for JavaScript
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.
RxJS - The Reactive extensions for JavaScript
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.
RxJS - The Reactive extensions for JavaScript
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...
RxJS - The Reactive extensions for JavaScript
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
RxJS - The Reactive extensions for JavaScript
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!"
RxJS - The Reactive extensions for JavaScript
.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));
?
?
?
?
?
?
?
?
RxJS - The Reactive extensions for JavaScript
.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 (20)

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
 
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 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
C4Media
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
MamoonKhan39
 
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
Ryan Anklam
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
Christoffer Noring
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
stefanmayer13
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
Alexander Mostovenko
 
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
Egor Andreevich
 
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
JSFestUA
 
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
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
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
Ben Lesh
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
Florent Pillet
 
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
Aaron Douglas
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
Duoyi Wu
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
Scott Gardner
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
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
 
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 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
C4Media
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
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
Ryan Anklam
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
stefanmayer13
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
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
Egor Andreevich
 
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
JSFestUA
 
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
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
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
Ben Lesh
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
Florent Pillet
 
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
Aaron Douglas
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
Duoyi Wu
 
Reactive Programming with RxSwift
Reactive Programming with RxSwiftReactive Programming with RxSwift
Reactive Programming with RxSwift
Scott Gardner
 

Viewers also liked (20)

Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScript
Jim Wooley
 
Reactive Programming and RxJS
Reactive Programming and RxJSReactive Programming and RxJS
Reactive Programming and RxJS
Denis Gorbunov
 
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
Lukas Ruebbelke
 
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!
Lukas Ruebbelke
 
ngAnimate crash course
ngAnimate crash coursengAnimate crash course
ngAnimate crash course
Lukas Ruebbelke
 
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
Lukas Ruebbelke
 
AngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTMLAngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTML
Lukas Ruebbelke
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
Lukas Ruebbelke
 
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
Lukas Ruebbelke
 
Vývojařská Plzeň - React
Vývojařská Plzeň - ReactVývojařská Plzeň - React
Vývojařská Plzeň - React
Viliam Elischer
 
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!
Viliam Elischer
 
The REAL Angular Keynote
The REAL Angular KeynoteThe REAL Angular Keynote
The REAL Angular Keynote
Lukas Ruebbelke
 
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
Viliam Elischer
 
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
Lukas Ruebbelke
 
FRP with Ractive and RxJS
FRP with Ractive and RxJSFRP with Ractive and RxJS
FRP with Ractive and RxJS
Alfonso Garcia-Caro
 
ReactiveX-SEA
ReactiveX-SEAReactiveX-SEA
ReactiveX-SEA
Yang Yang
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
Kevin Dantas
 
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
Wendel Nascimento
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
Sunscrapers
 
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
Lukas Ruebbelke
 
Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScript
Jim Wooley
 
Reactive Programming and RxJS
Reactive Programming and RxJSReactive Programming and RxJS
Reactive Programming and RxJS
Denis Gorbunov
 
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
Lukas Ruebbelke
 
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!
Lukas Ruebbelke
 
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
Lukas Ruebbelke
 
AngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTMLAngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTML
Lukas Ruebbelke
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
Lukas Ruebbelke
 
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
Lukas Ruebbelke
 
Vývojařská Plzeň - React
Vývojařská Plzeň - ReactVývojařská Plzeň - React
Vývojařská Plzeň - React
Viliam Elischer
 
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!
Viliam Elischer
 
The REAL Angular Keynote
The REAL Angular KeynoteThe REAL Angular Keynote
The REAL Angular Keynote
Lukas Ruebbelke
 
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
Viliam Elischer
 
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
Lukas Ruebbelke
 
ReactiveX-SEA
ReactiveX-SEAReactiveX-SEA
ReactiveX-SEA
Yang Yang
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
Kevin Dantas
 
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
Wendel Nascimento
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
Sunscrapers
 
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
Lukas Ruebbelke
 

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 - делаем асинхр...
GeeksLab Odessa
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
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
Oscar Renalias
 
Reactive x
Reactive xReactive x
Reactive x
Gabriel Araujo
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
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
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Abul Hasan
 
The Reactive Landscape
The Reactive LandscapeThe Reactive Landscape
The Reactive Landscape
Red Hat Developers
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
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...
Mario Fusco
 
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
Codemotion
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
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
MongoDB
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
Voislav Mishevski
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
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
Francois Zaninotto
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
Ryan Anklam
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
Christoffer Noring
 
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
 
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
Oscar Renalias
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
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
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Abul Hasan
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
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...
Mario Fusco
 
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
Codemotion
 
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
MongoDB
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
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
Francois Zaninotto
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
Ryan Anklam
 

Recently uploaded (20)

Supplier_PFMEA_Workshop_rev 22_04_27.pptx
Supplier_PFMEA_Workshop_rev 22_04_27.pptxSupplier_PFMEA_Workshop_rev 22_04_27.pptx
Supplier_PFMEA_Workshop_rev 22_04_27.pptx
dariojaen1977
 
22PCOAM16 Machine Learning Unit V Full notes & QB
22PCOAM16 Machine Learning Unit V Full notes & QB22PCOAM16 Machine Learning Unit V Full notes & QB
22PCOAM16 Machine Learning Unit V Full notes & QB
Guru Nanak Technical Institutions
 
Unit 6 Message Digest Message Digest Message Digest
Unit 6  Message Digest  Message Digest  Message DigestUnit 6  Message Digest  Message Digest  Message Digest
Unit 6 Message Digest Message Digest Message Digest
ChatanBawankar
 
Software Engineering Unit 2 Power Point Presentation AKTU University
Software Engineering Unit 2 Power Point Presentation AKTU UniversitySoftware Engineering Unit 2 Power Point Presentation AKTU University
Software Engineering Unit 2 Power Point Presentation AKTU University
utkarshpandey8299
 
1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf
VikasNirgude2
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Department of Environment (DOE) Mix Design with Fly Ash.
Department of Environment (DOE) Mix Design with Fly Ash.Department of Environment (DOE) Mix Design with Fly Ash.
Department of Environment (DOE) Mix Design with Fly Ash.
MdManikurRahman
 
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDINGMODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
Dr. Shivu___Machine Learning_Module 2pdf
Dr. Shivu___Machine Learning_Module 2pdfDr. Shivu___Machine Learning_Module 2pdf
Dr. Shivu___Machine Learning_Module 2pdf
Dr. Shivashankar
 
Internship_certificate_by_edunetfoundation.pdf
Internship_certificate_by_edunetfoundation.pdfInternship_certificate_by_edunetfoundation.pdf
Internship_certificate_by_edunetfoundation.pdf
prikshitgautam27
 
MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020
Bagus ardian
 
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdfSilent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
EfrainGarrilloRuiz1
 
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notesBEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
VarshithaP6
 
Java Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyondJava Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyond
arzu TR
 
HVAC Air Filter Equipment-Catalouge-Final.pdf
HVAC Air Filter Equipment-Catalouge-Final.pdfHVAC Air Filter Equipment-Catalouge-Final.pdf
HVAC Air Filter Equipment-Catalouge-Final.pdf
FILTRATION ENGINEERING & CUNSULTANT
 
THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...
THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...
THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...
ijfcstjournal
 
1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf
VikasNirgude2
 
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdfSoftware_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
VanshMunjal7
 
Supplier_PFMEA_Workshop_rev 22_04_27.pptx
Supplier_PFMEA_Workshop_rev 22_04_27.pptxSupplier_PFMEA_Workshop_rev 22_04_27.pptx
Supplier_PFMEA_Workshop_rev 22_04_27.pptx
dariojaen1977
 
Unit 6 Message Digest Message Digest Message Digest
Unit 6  Message Digest  Message Digest  Message DigestUnit 6  Message Digest  Message Digest  Message Digest
Unit 6 Message Digest Message Digest Message Digest
ChatanBawankar
 
Software Engineering Unit 2 Power Point Presentation AKTU University
Software Engineering Unit 2 Power Point Presentation AKTU UniversitySoftware Engineering Unit 2 Power Point Presentation AKTU University
Software Engineering Unit 2 Power Point Presentation AKTU University
utkarshpandey8299
 
1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf1.2 Need of Object-Oriented Programming.pdf
1.2 Need of Object-Oriented Programming.pdf
VikasNirgude2
 
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDINGMODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
MODULE 4 BUILDING PLANNING AND DESIGN SY BTECH HVAC SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
Department of Environment (DOE) Mix Design with Fly Ash.
Department of Environment (DOE) Mix Design with Fly Ash.Department of Environment (DOE) Mix Design with Fly Ash.
Department of Environment (DOE) Mix Design with Fly Ash.
MdManikurRahman
 
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDINGMODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
MODULE 5 BUILDING PLANNING AND DESIGN SY BTECH ACOUSTICS SYSTEM IN BUILDING
Dr. BASWESHWAR JIRWANKAR
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
Dr. Shivu___Machine Learning_Module 2pdf
Dr. Shivu___Machine Learning_Module 2pdfDr. Shivu___Machine Learning_Module 2pdf
Dr. Shivu___Machine Learning_Module 2pdf
Dr. Shivashankar
 
Internship_certificate_by_edunetfoundation.pdf
Internship_certificate_by_edunetfoundation.pdfInternship_certificate_by_edunetfoundation.pdf
Internship_certificate_by_edunetfoundation.pdf
prikshitgautam27
 
MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020MS Project - Pelaksanaan Proyek Fisik 2020
MS Project - Pelaksanaan Proyek Fisik 2020
Bagus ardian
 
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdfSilent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
Silent-Aire Quality Orientation - OFCI_GC - EVAP Unit REV2.pdf
EfrainGarrilloRuiz1
 
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notesBEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
BEC602- Module 3-2-Notes.pdf.Vlsi design and testing notes
VarshithaP6
 
Java Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyondJava Programming Language: until 2025 and beyond
Java Programming Language: until 2025 and beyond
arzu TR
 
THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...
THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...
THE RISK ASSESSMENT AND TREATMENT APPROACH IN ORDER TO PROVIDE LAN SECURITY B...
ijfcstjournal
 
1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf1.10 Functions in C++,call by value .pdf
1.10 Functions in C++,call by value .pdf
VikasNirgude2
 
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdfSoftware_Engineering_in_6_Hours_lyst1728638742594.pdf
Software_Engineering_in_6_Hours_lyst1728638742594.pdf
VanshMunjal7
 

RxJS - The Reactive extensions for JavaScript

  • 4. $ whoami Viliam Elischer SW Engineer at ZOOM International twitter.com/vireliam github.com/vire
  • 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.
  • 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.
  • 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...
  • 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));
  • 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!"
  • 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)); ? ? ? ? ? ? ? ?
  • 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