SlideShare a Scribd company logo
RxJS In-Depth
(Formerly a talk called
“Reactive Streams in Angular 1 and 2”)
We had a last-minute
pivot on talk content,
because Jeff Cross and
Rob Wormald wanted to
ruin my week last week.
Ben Lesh
Senior UI Engineer
Edge Developer Experience
RxJS Next
http://github.com/ReactiveX/RxJS
“RxJS Next”
is now
RxJS 5.0.0-alpha
RxJS 5 is community
driven
Spear-headed by contributors at Netflix, Google
and Microsoft. With many other contributors
under the ReactiveX community banner.
RxJS 5 Goals
• Performance
• Improved debugging
• ES7 observable spec alignment
Performance
• Decisions were guided by performance testing
• Tried out 4-5 different architectures in the
beginning
• > 120 micro performance tests
• ~ 10 macro performance tests around common
scenarios and bottlenecks
RxJS 5 operators are
4.3x faster on average
Call-stack depth and debugging
was a common complaint in older
versions of RxJS
RxJS 4
RxJS 5
Thanks in huge part to
contributions from
Paul Taylor OJ Kwon
André Staltz Jeff Cross
… really every one of our
contributors.
https://github.com/ReactiveX/RxJS/graphs/contributors
Thanks to guidance from
Matt Podwysocki Jafar Husain Erik Meijer
Ben Christensen George Campbell Aaron Tull
we’re closing in on beta
in the next month or so
What is RxJS?
• Reactive programming
• Treating events as collections
• Manipulating sets of events with ”operators”
“RxJS is LoDash or Underscore for async.”
Angular 2 is using
RxJS 5 Observables
for async
Angular has traditionally
used Promises for async
Promises
• Read-only view to a single future value
• Success and error semantics via .then()
• Not lazy. By the time you have a promise, it’s on
its way to being resolved.
• Immutable and uncancellable. Your promise will
resolve or reject, and only once.
Observable
• “Streams” or sets
• Of any number of things
• Over any amount of time
• Lazy. Observables will not generate values via an
underlying producer until they’re subscribed to.
• Can be “unsubscribed” from. This means the
underlying producer can be told to stop and even tear
down.
Both Promises and Observables
are built to solve problems
around async
(to avoid “callback hell”)
Types of async in modern
web applications
• DOM events
• Animations
• AJAX
• WebSockets
• SSE
• Alternative inputs (voice, joystick, etc)
Promises only really make
sense for one of these
• DOM events (0-N values)
• Animations (cancelable)
• AJAX (1 value)
• WebSockets (0-N values)
• SSE (0-N values)
• Alternative inputs (0-N values)
… except when they don’t
• Single page applications commonly prepare data
via AJAX for each view shown
• When the view changes, the next view probably
doesn’t care about the previous view’s data
• Fortunately, XHRs can be aborted!
• …but promise-based AJAX implementations
cannot be aborted, because promises cannot be
cancelled.*
So how do we go from
Promises to
Observables?
They have some similar
semantics
then x. (valueFn, errorFn);subscribe
They have some similar
semantics
x.subscribe(valueFn, errorFn);, completeFn
Observable also has
cancellation semantics!
let sub = x.subscribe(valueFn, errorFn, completeFn);
// ...some time later
sub.unsubscribe();
Creating Observables is
similar to creating
Promises
creating a Promise
let p = new Promise((resolve, reject) => {
doAsyncThing((err, value) => {
if (err) {
reject(err);
} else {
resolve(value);
}
});
});
creating an Observable
let o = new Observable(observer => {
doAsyncThing((err, value) => {
if (err) {
observer.error(err);
} else {
observer.next(value);
observer.complete();
}
});
});
if the producer’s resource
allows cancellation,
we can handle that here
let o = new Observable(observer => {
const token = doAsyncThing((err, value) => {
if (err) {
observer.error(err);
} else {
observer.next(value);
observer.complete();
}
});
});
const token
return () => {
cancelAsyncThing(token);
};
when you call o.subscribe()
let o = new Observable(observer => {
const token = doAsyncThing((err, value) => {
if (err) {
observer.error(err);
} else {
observer.next(value);
observer.complete();
}
});
return () => {
cancelAsyncThing(token);
};
});
observer => {
const token = doAsyncThing((err, value) => {
if (err) {
observer.error(err);
} else {
observer.next(value);
observer.complete();
}
});
return () => {
};
});
when you call
subscription.unsubscribe()
let o = new Observable(observer => {
const token = doAsyncThing((err, value) => {
if (err) {
observer.error(err);
} else {
observer.next(value);
observer.complete();
}
});
return () => {
cancelAsyncThing(token);
};
});
return () => {
cancelAsyncThing(token);
};
Don’t worry... you’re
unlikely to be creating
your own Observables
Observable creation
helpers in RxJS
• Observable.of(value, value2, value3, …)
• Observable.from(promise/iterable/observable)
• Observable.fromEvent(item, eventName)
• Angular’s HTTP and Realtime Data services
• Many community-driven RxJS modules and
libraries
Error Handling in
Observables is also
similar to Promise
catch
myPromise.catch(error => {
if (error instanceof OkayError) {
return Promise.resolve(‘okay’);
} else {
throw error;
}
});
catch
myObservable.catch(error => {
if (error instanceof OkayError) {
return Observable.of(‘okay’);
} else {
throw error;
}
});
finally
(some promise impls)
myPromise.finally(() => {
console.log(‘done’);
});
finally
myObservable.finally(() => {
console.log(‘done’);
});
Observables can be “retried”
myObservable.retry(3);
myObservable.retryWhen(errors =>
errors.delay(3000));
Quick Recap on
Observable
An observable is a set of any number of things over
any amount of time.
Quick Recap on
Observable
All values are pushed to the nextHandler
observable.subscribe(nextHandler);
Quick Recap on
Observable
The errorHandler is called if the producer
experiences an error
observable.subscribe(nextHandler, errorHandler);
Quick Recap on
Observable
The completionHandler is called when the producer
completes successfully
observable.subscribe(nextHandler, errorHandler, completionHandler);
Quick Recap on
Observable
Observables are lazy. It doesn’t start producing
data until subscribe() is called.
observable.subscribe(nextHandler, errorHandler, completionHandler);
Quick Recap on
Observable
subscribe() returns a subscription, on which a
consumer can call unsubscribe() to cancel the
subscription and tear down the producer
let sub = observable.subscribe(nextHandler, errorHandler, completionHandler);
sub.unsubscribe();
What are “operators”?
They’re methods on Observable that allow you to
compose new observables.
How operators work
let result = source.myOperator();
result is an Observable, that when subscribed to,
subscribes to source, then tranforms it’s values in
some way and emits them.
How operators work
subscription.unsubscribe();
when unsubscribe() is called on that
subscription, the unsubscription logic from both
result and source are called.
How operators work
• Operators pass each value from one operator to
the next, before proceeding to the next value in
the set.*
• This is different from array operators (think map
and filter) which will process the entire array at
each step.
• *This can be changed with Schedulers.
Array filter, map, reduce
Observable filter, map, reduce
simple operators
• map()
• filter()
• reduce()
• first()
• last()
• single()
• elementAt()
• toArray()
• isEmpty()
• take()
• skip()
• startWith()
• and many more…
merging and joining operators
• merge
• mergeMap (flatMap)
• concat
• concatMap
• switch
• switchMap
• combineLatest
• withLatestFrom
• zip
• forkJoin
• expand
splitting and grouping operators
• groupBy
• window
• partition
buffering strategy operators
• buffer
• throttle
• debounce
• sample
With ES7 function bind,
you can roll your own*
(*coming soon to TypeScript?)
“hot” vs “cold” observables
• Observables are “cold” by default
• “Cold” observables create a new producer each
time a consumer subscribes to them
• “Hot” observables share a single producer with
every consumer that subscribes to them.
Multiplexed WebSocket
• Connect to a web socket server
• For each data stream
• send a subscription message to the server
• filter out responses from the server
• when done, send an unsubscription message.
• Ideally, the socket is only open while you require data
from it.
Multiplexed WebSocket
• RECONNECTION?!
• maintain a state of all of the multiplexed data
streams your views need.
• check to see when you’re able to reconnect
• reconnect the socket
• once the socket is reopened, send all of the
subscription messages again
Create an Observable
that wraps a WebSocket
It will create the WebSocket
when you subscribe()
It emits messages events
that arrive on the WebSocket
And when it unsubscribes,
it will tear down the WebSocket!
“Share” to make it “hot”…
We don’t want each subscription
creating it’s own websocket.
Create an Observable
that wraps our
Socket Observable
filter the messages
from the Socket Observable
to what you need
and subscribe
Send a message to
the server to start getting
the data over the socket
on unsubscribe,
tell the server
to stop sending data
and unsubscribe
from the socket observable
Add a retryWhen to retry the whole thing
if something goes wrong with the multiplexed observable
“share” the observable to make it “hot”,
so many consumers can share this producer.
Example Time!
Never trust anyone with
only good things to say
about their
library/framework.
What’s bad in RxJS?
• “Zalgo”.. don’t use mutable outer scoped
variables in your operators or subscriptions!
• Unbounded buffers! The zip operator in particular
is dangerous here.
• Too many operators to remember.
Twitter: @benlesh
github: blesh
ben@benlesh.com
GOOD: Comments.
BETTER: Questions.
BEST: Corrections!
Thank you!
Ad

Recommended

PPTX
Advanced RxJS: Animations
Ben Lesh
 
PPTX
RxJS Animations Talk - 2017
Ben Lesh
 
PDF
Rethink Async With RXJS
Ryan Anklam
 
PPTX
Async Redux Actions With RxJS - React Rally 2016
Ben Lesh
 
PDF
My Gentle Introduction to RxJS
Mattia Occhiuto
 
PPTX
Rxjs ngvikings
Christoffer Noring
 
PDF
RxJS101 - What you need to know to get started with RxJS tomorrow
Viliam Elischer
 
PDF
Cascadia.js: Don't Cross the Streams
mattpodwysocki
 
PPTX
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
PDF
Introduction to RxJS
Brainhub
 
PPTX
RxJava Applied
Igor Lozynskyi
 
PDF
RxJS Operators - Real World Use Cases (FULL VERSION)
Tracy Lee
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PPTX
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
PDF
Angular and The Case for RxJS
Sandi Barr
 
PPTX
Connect S3 with Kafka using Akka Streams
Seiya Mizuno
 
PPTX
Luis Atencio on RxJS
Luis Atencio
 
PDF
ES6: The Awesome Parts
Domenic Denicola
 
PDF
Reactive programming on Android
Tomáš Kypta
 
PDF
Practical RxJava for Android
Tomáš Kypta
 
PDF
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
PDF
Practical RxJava for Android
Tomáš Kypta
 
PDF
RxJava for Android - GDG DevFest Ukraine 2015
Constantine Mars
 
PPTX
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
PDF
Reactive Thinking in Java
Yakov Fain
 
PDF
Callbacks and control flow in Node js
Thomas Roch
 
PDF
Understanding Asynchronous JavaScript
jnewmanux
 
ODP
Realm Mobile Database - An Introduction
Knoldus Inc.
 
PPTX
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
PPTX
Angular2 + rxjs
Christoffer Noring
 

More Related Content

What's hot (20)

PPTX
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
PDF
Introduction to RxJS
Brainhub
 
PPTX
RxJava Applied
Igor Lozynskyi
 
PDF
RxJS Operators - Real World Use Cases (FULL VERSION)
Tracy Lee
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PPTX
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
PDF
Angular and The Case for RxJS
Sandi Barr
 
PPTX
Connect S3 with Kafka using Akka Streams
Seiya Mizuno
 
PPTX
Luis Atencio on RxJS
Luis Atencio
 
PDF
ES6: The Awesome Parts
Domenic Denicola
 
PDF
Reactive programming on Android
Tomáš Kypta
 
PDF
Practical RxJava for Android
Tomáš Kypta
 
PDF
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
PDF
Practical RxJava for Android
Tomáš Kypta
 
PDF
RxJava for Android - GDG DevFest Ukraine 2015
Constantine Mars
 
PPTX
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
PDF
Reactive Thinking in Java
Yakov Fain
 
PDF
Callbacks and control flow in Node js
Thomas Roch
 
PDF
Understanding Asynchronous JavaScript
jnewmanux
 
ODP
Realm Mobile Database - An Introduction
Knoldus Inc.
 
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
Introduction to RxJS
Brainhub
 
RxJava Applied
Igor Lozynskyi
 
RxJS Operators - Real World Use Cases (FULL VERSION)
Tracy Lee
 
Avoiding Callback Hell with Async.js
cacois
 
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
Angular and The Case for RxJS
Sandi Barr
 
Connect S3 with Kafka using Akka Streams
Seiya Mizuno
 
Luis Atencio on RxJS
Luis Atencio
 
ES6: The Awesome Parts
Domenic Denicola
 
Reactive programming on Android
Tomáš Kypta
 
Practical RxJava for Android
Tomáš Kypta
 
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
Practical RxJava for Android
Tomáš Kypta
 
RxJava for Android - GDG DevFest Ukraine 2015
Constantine Mars
 
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
Reactive Thinking in Java
Yakov Fain
 
Callbacks and control flow in Node js
Thomas Roch
 
Understanding Asynchronous JavaScript
jnewmanux
 
Realm Mobile Database - An Introduction
Knoldus Inc.
 

Viewers also liked (20)

PPTX
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
PPTX
Angular2 + rxjs
Christoffer Noring
 
PPTX
Functional Reactive Programming with RxJS
stefanmayer13
 
PDF
ReactiveX-SEA
Yang Yang
 
PDF
RxJS Evolved
trxcllnt
 
PPTX
Rxjs ppt
Christoffer Noring
 
PPTX
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
PPTX
Building modular enterprise scale angular js applications
Jonathan Fontanez
 
PPTX
Observables in angular2
Filip Bruun Bech-Larsen
 
PDF
You will learn RxJS in 2017
名辰 洪
 
PDF
Angular 2 observables
Geoffrey Filippi
 
PPTX
Mini training - Reactive Extensions (Rx)
Betclic Everest Group Tech Team
 
PPTX
Angular2 rxjs
Christoffer Noring
 
PDF
FRP with Ractive and RxJS
Alfonso Garcia-Caro
 
PDF
Progressive Web Apps
Kevin Dantas
 
PDF
Programação reativa com RxJS e Angular
Wendel Nascimento
 
PDF
Add Some Fun to Your Functional Programming With RXJS
Ryan Anklam
 
PPTX
Reactive programming
Sunscrapers
 
PDF
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
PDF
Functional Reactive Angular 2
Tomasz Bak
 
RxJS and Reactive Programming - Modern Web UI - May 2015
Ben Lesh
 
Angular2 + rxjs
Christoffer Noring
 
Functional Reactive Programming with RxJS
stefanmayer13
 
ReactiveX-SEA
Yang Yang
 
RxJS Evolved
trxcllnt
 
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
Building modular enterprise scale angular js applications
Jonathan Fontanez
 
Observables in angular2
Filip Bruun Bech-Larsen
 
You will learn RxJS in 2017
名辰 洪
 
Angular 2 observables
Geoffrey Filippi
 
Mini training - Reactive Extensions (Rx)
Betclic Everest Group Tech Team
 
Angular2 rxjs
Christoffer Noring
 
FRP with Ractive and RxJS
Alfonso Garcia-Caro
 
Progressive Web Apps
Kevin Dantas
 
Programação reativa com RxJS e Angular
Wendel Nascimento
 
Add Some Fun to Your Functional Programming With RXJS
Ryan Anklam
 
Reactive programming
Sunscrapers
 
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Functional Reactive Angular 2
Tomasz Bak
 
Ad

Similar to RxJS In-Depth - AngularConnect 2015 (20)

PPTX
Introduction to RxJS
Abul Hasan
 
PDF
Observables in Angular
Knoldus Inc.
 
PDF
Rxjs kyivjs 2015
Alexander Mostovenko
 
PPTX
Rx – reactive extensions
Voislav Mishevski
 
PDF
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
PDF
rx.js make async programming simpler
Alexander Mostovenko
 
PPTX
Rxjs marble-testing
Christoffer Noring
 
PPTX
Rxjs swetugg
Christoffer Noring
 
PPTX
Taming Asynchrony using RxJS
Angelo Simone Scotto
 
PDF
Rxjs vienna
Christoffer Noring
 
PPTX
Promises, promises, and then observables
Stefan Charsley
 
PPTX
Angular mix chrisnoring
Christoffer Noring
 
PDF
DZone_RC_RxJS
Luis Atencio
 
PDF
Reactive x
Gabriel Araujo
 
PPTX
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
DevClub_lv
 
PPTX
Angular observables for fun and profit
Gil Steiner
 
PPTX
TDC2016SP - Trilha Node.Js
tdc-globalcode
 
PPTX
From zero to hero with the reactive extensions for java script
Maurice De Beijer [MVP]
 
PPTX
From zero to hero with the reactive extensions for JavaScript
Maurice De Beijer [MVP]
 
PDF
RxJava@DAUG
Maxim Volgin
 
Introduction to RxJS
Abul Hasan
 
Observables in Angular
Knoldus Inc.
 
Rxjs kyivjs 2015
Alexander Mostovenko
 
Rx – reactive extensions
Voislav Mishevski
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
GeeksLab Odessa
 
rx.js make async programming simpler
Alexander Mostovenko
 
Rxjs marble-testing
Christoffer Noring
 
Rxjs swetugg
Christoffer Noring
 
Taming Asynchrony using RxJS
Angelo Simone Scotto
 
Rxjs vienna
Christoffer Noring
 
Promises, promises, and then observables
Stefan Charsley
 
Angular mix chrisnoring
Christoffer Noring
 
DZone_RC_RxJS
Luis Atencio
 
Reactive x
Gabriel Araujo
 
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
DevClub_lv
 
Angular observables for fun and profit
Gil Steiner
 
TDC2016SP - Trilha Node.Js
tdc-globalcode
 
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
Maurice De Beijer [MVP]
 
RxJava@DAUG
Maxim Volgin
 
Ad

Recently uploaded (20)

PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PPTX
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
PPTX
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
PPTX
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
PDF
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
PDF
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
PDF
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
PDF
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
PDF
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
PDF
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
PDF
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
PDF
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
PPTX
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
PDF
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
PDF
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
PDF
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
PDF
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 

RxJS In-Depth - AngularConnect 2015

  • 1. RxJS In-Depth (Formerly a talk called “Reactive Streams in Angular 1 and 2”)
  • 2. We had a last-minute pivot on talk content, because Jeff Cross and Rob Wormald wanted to ruin my week last week.
  • 3. Ben Lesh Senior UI Engineer Edge Developer Experience
  • 6. RxJS 5 is community driven Spear-headed by contributors at Netflix, Google and Microsoft. With many other contributors under the ReactiveX community banner.
  • 7. RxJS 5 Goals • Performance • Improved debugging • ES7 observable spec alignment
  • 8. Performance • Decisions were guided by performance testing • Tried out 4-5 different architectures in the beginning • > 120 micro performance tests • ~ 10 macro performance tests around common scenarios and bottlenecks
  • 9. RxJS 5 operators are 4.3x faster on average
  • 10. Call-stack depth and debugging was a common complaint in older versions of RxJS
  • 13. Thanks in huge part to contributions from Paul Taylor OJ Kwon André Staltz Jeff Cross
  • 14. … really every one of our contributors. https://github.com/ReactiveX/RxJS/graphs/contributors
  • 15. Thanks to guidance from Matt Podwysocki Jafar Husain Erik Meijer Ben Christensen George Campbell Aaron Tull
  • 16. we’re closing in on beta in the next month or so
  • 17. What is RxJS? • Reactive programming • Treating events as collections • Manipulating sets of events with ”operators”
  • 18. “RxJS is LoDash or Underscore for async.”
  • 19. Angular 2 is using RxJS 5 Observables for async
  • 20. Angular has traditionally used Promises for async
  • 21. Promises • Read-only view to a single future value • Success and error semantics via .then() • Not lazy. By the time you have a promise, it’s on its way to being resolved. • Immutable and uncancellable. Your promise will resolve or reject, and only once.
  • 22. Observable • “Streams” or sets • Of any number of things • Over any amount of time • Lazy. Observables will not generate values via an underlying producer until they’re subscribed to. • Can be “unsubscribed” from. This means the underlying producer can be told to stop and even tear down.
  • 23. Both Promises and Observables are built to solve problems around async (to avoid “callback hell”)
  • 24. Types of async in modern web applications • DOM events • Animations • AJAX • WebSockets • SSE • Alternative inputs (voice, joystick, etc)
  • 25. Promises only really make sense for one of these • DOM events (0-N values) • Animations (cancelable) • AJAX (1 value) • WebSockets (0-N values) • SSE (0-N values) • Alternative inputs (0-N values)
  • 26. … except when they don’t • Single page applications commonly prepare data via AJAX for each view shown • When the view changes, the next view probably doesn’t care about the previous view’s data • Fortunately, XHRs can be aborted! • …but promise-based AJAX implementations cannot be aborted, because promises cannot be cancelled.*
  • 27. So how do we go from Promises to Observables?
  • 28. They have some similar semantics then x. (valueFn, errorFn);subscribe
  • 29. They have some similar semantics x.subscribe(valueFn, errorFn);, completeFn
  • 30. Observable also has cancellation semantics! let sub = x.subscribe(valueFn, errorFn, completeFn); // ...some time later sub.unsubscribe();
  • 31. Creating Observables is similar to creating Promises
  • 32. creating a Promise let p = new Promise((resolve, reject) => { doAsyncThing((err, value) => { if (err) { reject(err); } else { resolve(value); } }); });
  • 33. creating an Observable let o = new Observable(observer => { doAsyncThing((err, value) => { if (err) { observer.error(err); } else { observer.next(value); observer.complete(); } }); });
  • 34. if the producer’s resource allows cancellation, we can handle that here let o = new Observable(observer => { const token = doAsyncThing((err, value) => { if (err) { observer.error(err); } else { observer.next(value); observer.complete(); } }); }); const token return () => { cancelAsyncThing(token); };
  • 35. when you call o.subscribe() let o = new Observable(observer => { const token = doAsyncThing((err, value) => { if (err) { observer.error(err); } else { observer.next(value); observer.complete(); } }); return () => { cancelAsyncThing(token); }; }); observer => { const token = doAsyncThing((err, value) => { if (err) { observer.error(err); } else { observer.next(value); observer.complete(); } }); return () => { }; });
  • 36. when you call subscription.unsubscribe() let o = new Observable(observer => { const token = doAsyncThing((err, value) => { if (err) { observer.error(err); } else { observer.next(value); observer.complete(); } }); return () => { cancelAsyncThing(token); }; }); return () => { cancelAsyncThing(token); };
  • 37. Don’t worry... you’re unlikely to be creating your own Observables
  • 38. Observable creation helpers in RxJS • Observable.of(value, value2, value3, …) • Observable.from(promise/iterable/observable) • Observable.fromEvent(item, eventName) • Angular’s HTTP and Realtime Data services • Many community-driven RxJS modules and libraries
  • 39. Error Handling in Observables is also similar to Promise
  • 40. catch myPromise.catch(error => { if (error instanceof OkayError) { return Promise.resolve(‘okay’); } else { throw error; } });
  • 41. catch myObservable.catch(error => { if (error instanceof OkayError) { return Observable.of(‘okay’); } else { throw error; } });
  • 42. finally (some promise impls) myPromise.finally(() => { console.log(‘done’); });
  • 44. Observables can be “retried” myObservable.retry(3); myObservable.retryWhen(errors => errors.delay(3000));
  • 45. Quick Recap on Observable An observable is a set of any number of things over any amount of time.
  • 46. Quick Recap on Observable All values are pushed to the nextHandler observable.subscribe(nextHandler);
  • 47. Quick Recap on Observable The errorHandler is called if the producer experiences an error observable.subscribe(nextHandler, errorHandler);
  • 48. Quick Recap on Observable The completionHandler is called when the producer completes successfully observable.subscribe(nextHandler, errorHandler, completionHandler);
  • 49. Quick Recap on Observable Observables are lazy. It doesn’t start producing data until subscribe() is called. observable.subscribe(nextHandler, errorHandler, completionHandler);
  • 50. Quick Recap on Observable subscribe() returns a subscription, on which a consumer can call unsubscribe() to cancel the subscription and tear down the producer let sub = observable.subscribe(nextHandler, errorHandler, completionHandler); sub.unsubscribe();
  • 51. What are “operators”? They’re methods on Observable that allow you to compose new observables.
  • 52. How operators work let result = source.myOperator(); result is an Observable, that when subscribed to, subscribes to source, then tranforms it’s values in some way and emits them.
  • 53. How operators work subscription.unsubscribe(); when unsubscribe() is called on that subscription, the unsubscription logic from both result and source are called.
  • 54. How operators work • Operators pass each value from one operator to the next, before proceeding to the next value in the set.* • This is different from array operators (think map and filter) which will process the entire array at each step. • *This can be changed with Schedulers.
  • 57. simple operators • map() • filter() • reduce() • first() • last() • single() • elementAt() • toArray() • isEmpty() • take() • skip() • startWith() • and many more…
  • 58. merging and joining operators • merge • mergeMap (flatMap) • concat • concatMap • switch • switchMap • combineLatest • withLatestFrom • zip • forkJoin • expand
  • 59. splitting and grouping operators • groupBy • window • partition
  • 60. buffering strategy operators • buffer • throttle • debounce • sample
  • 61. With ES7 function bind, you can roll your own* (*coming soon to TypeScript?)
  • 62. “hot” vs “cold” observables • Observables are “cold” by default • “Cold” observables create a new producer each time a consumer subscribes to them • “Hot” observables share a single producer with every consumer that subscribes to them.
  • 63. Multiplexed WebSocket • Connect to a web socket server • For each data stream • send a subscription message to the server • filter out responses from the server • when done, send an unsubscription message. • Ideally, the socket is only open while you require data from it.
  • 64. Multiplexed WebSocket • RECONNECTION?! • maintain a state of all of the multiplexed data streams your views need. • check to see when you’re able to reconnect • reconnect the socket • once the socket is reopened, send all of the subscription messages again
  • 65. Create an Observable that wraps a WebSocket
  • 66. It will create the WebSocket when you subscribe()
  • 67. It emits messages events that arrive on the WebSocket
  • 68. And when it unsubscribes, it will tear down the WebSocket!
  • 69. “Share” to make it “hot”… We don’t want each subscription creating it’s own websocket.
  • 70. Create an Observable that wraps our Socket Observable
  • 71. filter the messages from the Socket Observable to what you need and subscribe
  • 72. Send a message to the server to start getting the data over the socket
  • 73. on unsubscribe, tell the server to stop sending data and unsubscribe from the socket observable
  • 74. Add a retryWhen to retry the whole thing if something goes wrong with the multiplexed observable
  • 75. “share” the observable to make it “hot”, so many consumers can share this producer.
  • 77. Never trust anyone with only good things to say about their library/framework.
  • 78. What’s bad in RxJS? • “Zalgo”.. don’t use mutable outer scoped variables in your operators or subscriptions! • Unbounded buffers! The zip operator in particular is dangerous here. • Too many operators to remember.
  • 79. Twitter: @benlesh github: blesh [email protected] GOOD: Comments. BETTER: Questions. BEST: Corrections! Thank you!

Editor's Notes

  • #14: Luis Gabriel Adrian Omelo Jinroh Rob Wormwald