SlideShare una empresa de Scribd logo
1 de 39
Functional Reactive Programming:
Working with RxJS
Oswald Campesato
Consultant/Training:
www.iquarkt.com
ocampesato@yahoo.com
What is Functional Reactive Programming (FRP)?
• 1) Functional programming:
• is more declarative
• often has more abstraction
• can involve higher order functions
• 2) Reactive Programming was introduced in 1997:
“programming with asynchronous data streams”
• Multiple toolkits/libraries available
• Supported languages JS, Java, Scala, Android, Swift, Go, ....
NB: Elm is an FRP language: http://elm-lang.org/
What is Functional Reactive Programming (FRP)?
A) Functional Reactive Programming:
• a programming paradigm that was created by Conal Elliott
• his definition has very specific semantics:
• https://stackoverflow.com/questions/1028250/what-is-
functional-reactive-programming
B) looser definition of FRP: a combination of 2 other concepts:
• Reactive Programming: focuses on asynchronous data streams,
which you can listen to and react accordingly
• Functional Programming: emphasizes calculations via
mathematical-style functions, immutability and expressiveness,
and minimizes the use of variables and state
Popular Toolkits/Libraries for FRP
• RxJS:
https://github.com/Reactive-Extensions/RxJS
• Bacon.js:
https://baconjs.github.io/
• Kefir.js:
https://rpominov.github.io/kefir/
• most.js:
https://github.com/cujojs/most
Promises versus RxJS
• "Promises are good for solving asynchronous
operations such as querying a service with an
XMLHttpRequest, where the expected behavior is
one value and then completion.”
• "RxJS unifies both the world of Promises, callbacks
as well as evented data such as DOM Input, Web
Workers, Web Sockets.”
• Support for Web Sockets in RxJS version 5(?)
How You can Use Observables in RxJS
• Orchestrate asynchronous data streams
• handle streams of data of indeterminate length
• Respond to mouse events and button clicks
• Generate SVG graphics/animation
• Combine with Promises (Rx.Observable.fromPromise())
• integrate with Angular 2, jQuery, …
A Vague Description of some Parts of FRP
• Obtain streams of data from many sources:
an array, list, function, website, ...
• define the required operations via operators
• operators include: map() and filter()
• method chaining of operators is supported
• invoke subscribe() to “make it happen”
Using ‘map’ and ‘filter’ (WITHOUT FRP)
• var source = [0,1,2,3,4,5,6,7,8,9,10];
• var result1 = source.map(x => x*x)
• .filter(x => x % 5 == 0);
• console.log("result1: "+result1);
• // output=?
• var result2 = source.filter(x => x % 5 == 0)
• .map(x => x*x)
• // output=?
• Q: what is the difference between these two?
Core JavaScript Files for RxJS (version 4)
<script
src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.js">
</script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.async
.js">
</script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.bindi
ng.js">
</script>
JavaScript Files for some Operators in RxJS
• <script
src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.tim
e.js">
• </script>
• <script
src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.coi
ncidence.js">
• </script>
• <script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs-
dom/2.0.7/rx.dom.js">
• </script>
What are Observables?
• Think of them as “streams” or sets
• Can comprise any number of items (arbitrary time)
• They generate values when they are “subscribed”
• Can be cancelled and restarted
• their purpose is to avoid “callback hell”
• “unsubscribe” will “tear down” a producer
How do Observables Work?
• Let x = Rx.Observable.(...)
• Let result = x.subscribe(valueFn, errorFn, CompleteFn)
• Do various things here...
• result.unsubscribe();
Observable Creation in RxJS
Observable.of(...)
Observable.from(promise/iterable/observable);
Observable.fromEvent(...)
Observables from HTTP in Angular 2
Additional RxJS modules/libraries
Operators in Observables
+ Operators are methods in Observables
+ Operators allow you to compose new observables
+ Create custom operators based on RxJS operators:
Rx.Observable.prototype.myGreatOperator = ....
General syntax of Observable operators:
let obs = Rx.Observable
.firstOperator()
.secondOperator()
.evenMoreOperatorsIfYouWant()
.subscribe(....); // now stuff happens=
Result:
obs is an Observable “connected” to a source
Using Observable, ‘range’, and ‘filter’ in RxJS
• var source = Rx.Observable
• .range(0, 20)
• .filter(x => x < 4)
• //output=?
• var source = Rx.Observable
• .range(0, 20)
• .filter(x => x < 4)
• .subscribe(x => console.log("x = "+x))
• //output=?
// ObservableRangeFilter1.html
Using ‘from’ and ‘map’ in RxJS (2a)
• Rx.Observable
• .from(['a1','a2','a3'])
• .map((item) => {
• item = item.toUpperCase()+item;
• return item;
• })
• .subscribe(str => console.log("item: "+str));
• // output:
A1a1
A2a2
A3a3
// ObservableMapUpper1.html
Using ‘from’ and ‘map’ in RxJS (2b)
var x = Rx.Observable
• .from(['a1','a2','a3'])
• .map((item) => {
• item = item.toUpperCase()+item;
• return item;
• })
x.subscribe(str => console.log("item: "+str));
// output:
A1a1
A2a2
A3a3
Observables: Exercises #1
• Modify ObservableMapUpper1.html in the exercises
1) Display the array elements in reverse order
2) Prepend the terminal digit and generate this output:
1a1, 2a2, 3a3
3) Concatenate the elements of the input array
Using ‘interval’, ‘take’, and ‘map’ in RxJS (3a)
// ObservableTake.html
var source = Rx.Observable
.interval(1000)
.take(4)
.map(i => ['1','2','3','4','5'][i]);
var result = source.subscribe(x => console.log("x = "+x));
// output =?
Using ‘interval’, ‘take’, and ‘map’ in RxJS (3b)
var source2 = Rx.Observable
.interval(1000)
.take(4)
.map(i => ['1','2','3','4','5'][i]);
var subscription = source2.subscribe(
x => console.log('source2 onNext: %s', x),
e => console.log('source2 onError: %s', e),
() => console.log('source2 onCompleted'));
• // output =?
Using ‘interval’, ‘take’, and ‘map’ in RxJS (3c)
• Output from BOTH observables is interleaved:
• x = 1
• source2 onNext: 1
• x = 2
• source2 onNext: 2
• x = 3
• source2 onNext: 3
• x = 4
• source2 onNext: 4
• source2 onCompleted
Observables: Exercises #2
• Modify ObservableTake.html in the exercises
1) Change the second 1000 to 500 and predict the outcome
2) Emit only even numbers from the first Observable
3) Compute squares of odd numbers in the second
Observable
Modify HTML Content via Observables (1)
// ObservableDivElement1.html
<div id="div1">This is a DIV element</div>
<script>
• let div1 = document.querySelector('#div1')
• var stream = Rx.Observable
• .interval(500)
• .take(10)
• .map(x => x*x)
• .subscribe(x => div1.innerHTML += x);
</script>
Modify HTML Content via Observables (2)
// ObservableDivElement2.html
<div id="div1">This is a DIV element</div>
<div id="div2">This is a DIV element</div>
<script>
let div1 = document.querySelector('#div1')
let div2 = document.querySelector('#div2')
var stream = Rx.Observable
.interval(500)
.take(10)
.map(x => x*x)
.subscribe(x => {
div1.innerHTML += x;
div2.innerHTML += x;
})
</script>
Observables and SVG Graphics/Animation
1) Observables and SVG graphics:
// SVGObservables1.html
2) Observables and SVG animation:
// SVGObservables1Anim1.html
3) Observables and SVG “follow the mouse”:
// SVGObservables1MouseMove1.html
4) Rxjs and SVG graphics/animation:
https://github.com/ocampesato/rxjs-svg-graphics
Some Available Operators
map() <= we’ve seen this in Angular 2
filter() <= we’ve seen this in Angular 2
reduce()
first()
last()
take()
skip()
toArray()
isEmpty()
startWith()
Observables: Exercises #3
• Modify: ObservableMapUpper1.html
1) Create an Observable with the first() operator
2) Create an Observable with the last() operator
3) What does this Observable emit:
var source = Rx.Observable
.return(8)
.startWith(1, 2, 3)
.subscribe(x => console.log("x = "+x));
Merging/Joining Operators
merge()
mergeMap()
concat()
concatMap()
switch()
switchMap()
zip()
forkJoin() <= requests from multiple sites are merged
withLatestFrom()
combineLatest()
Map-Related Operators
map()
flatMap()
flatMapLatest()
mergeMap()
concatMap()
switchMap()
flatten() <= this is different from flatMap*()
Map-Related Operators
• map(): items of the observable are mapped or
transformed into something else
• flatMap() (several variants): takes a function
returning an observable from each item of the source
observable, which produces makes a stream of
streams (where stream = observable = sequence of
items), and is "flattened" into a single stream /
observable by flapMap
• flatMapLatest(): a flatMap where only the items of
the current observable are emitted: if a new
observable appears, then the values of the previous
observable are ignored.
Map-Related Operators
• concatMap(): uses concat() so that intermediate
results are not 'interleaved', which can happen
with flatMap() because the latter uses merge()
• merge(): combine multiple Observables into one
(interleaving can occur)
• concat(): combine multiple Observables
sequentially into one (no interleaving occurs)
Observables: Exercises #4 (self-study)
1) Create an Observable with the merge() operator
2) Create an Observable with the zip() operator
3) Create an Observable with the concat() operator
“Hot” versus “Cold” Observables
“cold” observables:
a new producer for each consumer
similar to watching a recorded movie
“hot” observables:
one producer for many consumers
similar to watching a live stream
invoke “publish” to make an observable “hot”
=> all observables are “cold” by default
From Promises to Observables
// define a Promise:
var p = new Promise();
// define an Observable from the Promise p:
var x = Observable.fromPromise(p);
// do something with x ...
Error Handling with Observables: catch
myObservable.catch( error => {
if(error instanceof MyError) {
return Observable.of(“MyError”);
} else {
throw error;
});
myObservable.finally(() => {
console.log(“done”);
});
Retrying Observables
myObservable.retry(3);
myObservable.retryWhen(errors =>
errors.delay(3000));
Note 1: unsubscribe enables the Observer to instruct
the Observable to ‘tear down’
Note 2: completion handler enables the Observable to
indicate that it has completed successfully
Creating an Observable in v5
let obs = new Observable(observer => {
myAsyncMethod((err,value) => {
if(err) {
observer.error(err);
} else {
observer.next(value); // older v4: onNext
observer.complete(); // older v4: onComplete
}
});
});
NB: ‘on’ prefix has been dropped in v5
Further Samples and Reading
1) Create a toggle button with RxJS:
https://www.themarketingtechnologist.co/create-a-
simple-toggle-button-with-rxjs-using-scan-and-startwith/
2) RxJS and mouse events:
http://jsfiddle.net/dinkleburg/ay8afp5f
3) http://reactivex.io/learnrx/
4) http://rxmarble.com
5) http://cycle.js.org/basic-examples.html
Recent/Upcoming Books and Training
1) HTML5 Canvas and CSS3 Graphics (2013)
2) jQuery, CSS3, and HTML5 for Mobile (2013)
3) HTML5 Pocket Primer (2013)
4) jQuery Pocket Primer (2013)
5) HTML5 Mobile Pocket Primer (2014)
6) D3 Pocket Primer (2015)
7) Python Pocket Primer (2015)
8) SVG Pocket Primer (2016)
9) CSS3 Pocket Primer (2016)
10) Angular 2 Pocket Primer (2016)

Más contenido relacionado

La actualidad más candente

Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Susan Potter
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기Wanbok Choi
 
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
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in PracticeOutware Mobile
 
ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherColin Eberhardt
 
A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to RxAndrey Cheptsov
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & CollectionsCocoaHeads France
 
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 AndroidEgor Andreevich
 

La actualidad más candente (20)

Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 
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...
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better Together
 
A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to Rx
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
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
 

Similar a Functional Reactive Programming (FRP): Working with RxJS

Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法x1 ichi
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a clusterGal Marder
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in JavaYakov Fain
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsKevin Webber
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015Ben Lesh
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
Basic R Learning
Basic R LearningBasic R Learning
Basic R LearningKumar P
 

Similar a Functional Reactive Programming (FRP): Working with RxJS (20)

Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
JS Essence
JS EssenceJS Essence
JS Essence
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
 
Reactive Thinking in Java
Reactive Thinking in JavaReactive Thinking in Java
Reactive Thinking in Java
 
Angular2
Angular2Angular2
Angular2
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Advanced r
Advanced rAdvanced r
Advanced r
 
Basic R Learning
Basic R LearningBasic R Learning
Basic R Learning
 
Advanced R cheat sheet
Advanced R cheat sheetAdvanced R cheat sheet
Advanced R cheat sheet
 
advancedR.pdf
advancedR.pdfadvancedR.pdf
advancedR.pdf
 

Más de Oswald Campesato

Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)Oswald Campesato
 
Introduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasIntroduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasOswald Campesato
 
Introduction to Deep Learning
Introduction to Deep LearningIntroduction to Deep Learning
Introduction to Deep LearningOswald Campesato
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2Oswald Campesato
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2Oswald Campesato
 
"An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning""An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning"Oswald Campesato
 
Introduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and TensorflowIntroduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and TensorflowOswald Campesato
 
Introduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-ProgrammersIntroduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-ProgrammersOswald Campesato
 
TensorFlow in Your Browser
TensorFlow in Your BrowserTensorFlow in Your Browser
TensorFlow in Your BrowserOswald Campesato
 
Deep Learning in Your Browser
Deep Learning in Your BrowserDeep Learning in Your Browser
Deep Learning in Your BrowserOswald Campesato
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlowOswald Campesato
 
Introduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlowIntroduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlowOswald Campesato
 
Intro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.jsIntro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.jsOswald Campesato
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlowOswald Campesato
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowOswald Campesato
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and SparkOswald Campesato
 
Deep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGLDeep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGLOswald Campesato
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowOswald Campesato
 

Más de Oswald Campesato (20)

Working with tf.data (TF 2)
Working with tf.data (TF 2)Working with tf.data (TF 2)
Working with tf.data (TF 2)
 
Introduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and KerasIntroduction to TensorFlow 2 and Keras
Introduction to TensorFlow 2 and Keras
 
Introduction to Deep Learning
Introduction to Deep LearningIntroduction to Deep Learning
Introduction to Deep Learning
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2
 
Introduction to TensorFlow 2
Introduction to TensorFlow 2Introduction to TensorFlow 2
Introduction to TensorFlow 2
 
"An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning""An Introduction to AI and Deep Learning"
"An Introduction to AI and Deep Learning"
 
H2 o berkeleydltf
H2 o berkeleydltfH2 o berkeleydltf
H2 o berkeleydltf
 
Introduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and TensorflowIntroduction to Deep Learning, Keras, and Tensorflow
Introduction to Deep Learning, Keras, and Tensorflow
 
Introduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-ProgrammersIntroduction to Deep Learning for Non-Programmers
Introduction to Deep Learning for Non-Programmers
 
TensorFlow in Your Browser
TensorFlow in Your BrowserTensorFlow in Your Browser
TensorFlow in Your Browser
 
Deep Learning in Your Browser
Deep Learning in Your BrowserDeep Learning in Your Browser
Deep Learning in Your Browser
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Introduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlowIntroduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlow
 
Intro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.jsIntro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.js
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and Tensorflow
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
 
Deep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGLDeep Learning in your Browser: powered by WebGL
Deep Learning in your Browser: powered by WebGL
 
Deep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlowDeep Learning, Keras, and TensorFlow
Deep Learning, Keras, and TensorFlow
 
C++ and Deep Learning
C++ and Deep LearningC++ and Deep Learning
C++ and Deep Learning
 

Último

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 

Último (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 

Functional Reactive Programming (FRP): Working with RxJS

  • 1. Functional Reactive Programming: Working with RxJS Oswald Campesato Consultant/Training: www.iquarkt.com ocampesato@yahoo.com
  • 2. What is Functional Reactive Programming (FRP)? • 1) Functional programming: • is more declarative • often has more abstraction • can involve higher order functions • 2) Reactive Programming was introduced in 1997: “programming with asynchronous data streams” • Multiple toolkits/libraries available • Supported languages JS, Java, Scala, Android, Swift, Go, .... NB: Elm is an FRP language: http://elm-lang.org/
  • 3. What is Functional Reactive Programming (FRP)? A) Functional Reactive Programming: • a programming paradigm that was created by Conal Elliott • his definition has very specific semantics: • https://stackoverflow.com/questions/1028250/what-is- functional-reactive-programming B) looser definition of FRP: a combination of 2 other concepts: • Reactive Programming: focuses on asynchronous data streams, which you can listen to and react accordingly • Functional Programming: emphasizes calculations via mathematical-style functions, immutability and expressiveness, and minimizes the use of variables and state
  • 4. Popular Toolkits/Libraries for FRP • RxJS: https://github.com/Reactive-Extensions/RxJS • Bacon.js: https://baconjs.github.io/ • Kefir.js: https://rpominov.github.io/kefir/ • most.js: https://github.com/cujojs/most
  • 5. Promises versus RxJS • "Promises are good for solving asynchronous operations such as querying a service with an XMLHttpRequest, where the expected behavior is one value and then completion.” • "RxJS unifies both the world of Promises, callbacks as well as evented data such as DOM Input, Web Workers, Web Sockets.” • Support for Web Sockets in RxJS version 5(?)
  • 6. How You can Use Observables in RxJS • Orchestrate asynchronous data streams • handle streams of data of indeterminate length • Respond to mouse events and button clicks • Generate SVG graphics/animation • Combine with Promises (Rx.Observable.fromPromise()) • integrate with Angular 2, jQuery, …
  • 7. A Vague Description of some Parts of FRP • Obtain streams of data from many sources: an array, list, function, website, ... • define the required operations via operators • operators include: map() and filter() • method chaining of operators is supported • invoke subscribe() to “make it happen”
  • 8. Using ‘map’ and ‘filter’ (WITHOUT FRP) • var source = [0,1,2,3,4,5,6,7,8,9,10]; • var result1 = source.map(x => x*x) • .filter(x => x % 5 == 0); • console.log("result1: "+result1); • // output=? • var result2 = source.filter(x => x % 5 == 0) • .map(x => x*x) • // output=? • Q: what is the difference between these two?
  • 9. Core JavaScript Files for RxJS (version 4) <script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.js"> </script> <script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.async .js"> </script> <script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.bindi ng.js"> </script>
  • 10. JavaScript Files for some Operators in RxJS • <script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.tim e.js"> • </script> • <script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.coi ncidence.js"> • </script> • <script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs- dom/2.0.7/rx.dom.js"> • </script>
  • 11. What are Observables? • Think of them as “streams” or sets • Can comprise any number of items (arbitrary time) • They generate values when they are “subscribed” • Can be cancelled and restarted • their purpose is to avoid “callback hell” • “unsubscribe” will “tear down” a producer
  • 12. How do Observables Work? • Let x = Rx.Observable.(...) • Let result = x.subscribe(valueFn, errorFn, CompleteFn) • Do various things here... • result.unsubscribe();
  • 13. Observable Creation in RxJS Observable.of(...) Observable.from(promise/iterable/observable); Observable.fromEvent(...) Observables from HTTP in Angular 2 Additional RxJS modules/libraries
  • 14. Operators in Observables + Operators are methods in Observables + Operators allow you to compose new observables + Create custom operators based on RxJS operators: Rx.Observable.prototype.myGreatOperator = .... General syntax of Observable operators: let obs = Rx.Observable .firstOperator() .secondOperator() .evenMoreOperatorsIfYouWant() .subscribe(....); // now stuff happens= Result: obs is an Observable “connected” to a source
  • 15. Using Observable, ‘range’, and ‘filter’ in RxJS • var source = Rx.Observable • .range(0, 20) • .filter(x => x < 4) • //output=? • var source = Rx.Observable • .range(0, 20) • .filter(x => x < 4) • .subscribe(x => console.log("x = "+x)) • //output=? // ObservableRangeFilter1.html
  • 16. Using ‘from’ and ‘map’ in RxJS (2a) • Rx.Observable • .from(['a1','a2','a3']) • .map((item) => { • item = item.toUpperCase()+item; • return item; • }) • .subscribe(str => console.log("item: "+str)); • // output: A1a1 A2a2 A3a3 // ObservableMapUpper1.html
  • 17. Using ‘from’ and ‘map’ in RxJS (2b) var x = Rx.Observable • .from(['a1','a2','a3']) • .map((item) => { • item = item.toUpperCase()+item; • return item; • }) x.subscribe(str => console.log("item: "+str)); // output: A1a1 A2a2 A3a3
  • 18. Observables: Exercises #1 • Modify ObservableMapUpper1.html in the exercises 1) Display the array elements in reverse order 2) Prepend the terminal digit and generate this output: 1a1, 2a2, 3a3 3) Concatenate the elements of the input array
  • 19. Using ‘interval’, ‘take’, and ‘map’ in RxJS (3a) // ObservableTake.html var source = Rx.Observable .interval(1000) .take(4) .map(i => ['1','2','3','4','5'][i]); var result = source.subscribe(x => console.log("x = "+x)); // output =?
  • 20. Using ‘interval’, ‘take’, and ‘map’ in RxJS (3b) var source2 = Rx.Observable .interval(1000) .take(4) .map(i => ['1','2','3','4','5'][i]); var subscription = source2.subscribe( x => console.log('source2 onNext: %s', x), e => console.log('source2 onError: %s', e), () => console.log('source2 onCompleted')); • // output =?
  • 21. Using ‘interval’, ‘take’, and ‘map’ in RxJS (3c) • Output from BOTH observables is interleaved: • x = 1 • source2 onNext: 1 • x = 2 • source2 onNext: 2 • x = 3 • source2 onNext: 3 • x = 4 • source2 onNext: 4 • source2 onCompleted
  • 22. Observables: Exercises #2 • Modify ObservableTake.html in the exercises 1) Change the second 1000 to 500 and predict the outcome 2) Emit only even numbers from the first Observable 3) Compute squares of odd numbers in the second Observable
  • 23. Modify HTML Content via Observables (1) // ObservableDivElement1.html <div id="div1">This is a DIV element</div> <script> • let div1 = document.querySelector('#div1') • var stream = Rx.Observable • .interval(500) • .take(10) • .map(x => x*x) • .subscribe(x => div1.innerHTML += x); </script>
  • 24. Modify HTML Content via Observables (2) // ObservableDivElement2.html <div id="div1">This is a DIV element</div> <div id="div2">This is a DIV element</div> <script> let div1 = document.querySelector('#div1') let div2 = document.querySelector('#div2') var stream = Rx.Observable .interval(500) .take(10) .map(x => x*x) .subscribe(x => { div1.innerHTML += x; div2.innerHTML += x; }) </script>
  • 25. Observables and SVG Graphics/Animation 1) Observables and SVG graphics: // SVGObservables1.html 2) Observables and SVG animation: // SVGObservables1Anim1.html 3) Observables and SVG “follow the mouse”: // SVGObservables1MouseMove1.html 4) Rxjs and SVG graphics/animation: https://github.com/ocampesato/rxjs-svg-graphics
  • 26. Some Available Operators map() <= we’ve seen this in Angular 2 filter() <= we’ve seen this in Angular 2 reduce() first() last() take() skip() toArray() isEmpty() startWith()
  • 27. Observables: Exercises #3 • Modify: ObservableMapUpper1.html 1) Create an Observable with the first() operator 2) Create an Observable with the last() operator 3) What does this Observable emit: var source = Rx.Observable .return(8) .startWith(1, 2, 3) .subscribe(x => console.log("x = "+x));
  • 28. Merging/Joining Operators merge() mergeMap() concat() concatMap() switch() switchMap() zip() forkJoin() <= requests from multiple sites are merged withLatestFrom() combineLatest()
  • 30. Map-Related Operators • map(): items of the observable are mapped or transformed into something else • flatMap() (several variants): takes a function returning an observable from each item of the source observable, which produces makes a stream of streams (where stream = observable = sequence of items), and is "flattened" into a single stream / observable by flapMap • flatMapLatest(): a flatMap where only the items of the current observable are emitted: if a new observable appears, then the values of the previous observable are ignored.
  • 31. Map-Related Operators • concatMap(): uses concat() so that intermediate results are not 'interleaved', which can happen with flatMap() because the latter uses merge() • merge(): combine multiple Observables into one (interleaving can occur) • concat(): combine multiple Observables sequentially into one (no interleaving occurs)
  • 32. Observables: Exercises #4 (self-study) 1) Create an Observable with the merge() operator 2) Create an Observable with the zip() operator 3) Create an Observable with the concat() operator
  • 33. “Hot” versus “Cold” Observables “cold” observables: a new producer for each consumer similar to watching a recorded movie “hot” observables: one producer for many consumers similar to watching a live stream invoke “publish” to make an observable “hot” => all observables are “cold” by default
  • 34. From Promises to Observables // define a Promise: var p = new Promise(); // define an Observable from the Promise p: var x = Observable.fromPromise(p); // do something with x ...
  • 35. Error Handling with Observables: catch myObservable.catch( error => { if(error instanceof MyError) { return Observable.of(“MyError”); } else { throw error; }); myObservable.finally(() => { console.log(“done”); });
  • 36. Retrying Observables myObservable.retry(3); myObservable.retryWhen(errors => errors.delay(3000)); Note 1: unsubscribe enables the Observer to instruct the Observable to ‘tear down’ Note 2: completion handler enables the Observable to indicate that it has completed successfully
  • 37. Creating an Observable in v5 let obs = new Observable(observer => { myAsyncMethod((err,value) => { if(err) { observer.error(err); } else { observer.next(value); // older v4: onNext observer.complete(); // older v4: onComplete } }); }); NB: ‘on’ prefix has been dropped in v5
  • 38. Further Samples and Reading 1) Create a toggle button with RxJS: https://www.themarketingtechnologist.co/create-a- simple-toggle-button-with-rxjs-using-scan-and-startwith/ 2) RxJS and mouse events: http://jsfiddle.net/dinkleburg/ay8afp5f 3) http://reactivex.io/learnrx/ 4) http://rxmarble.com 5) http://cycle.js.org/basic-examples.html
  • 39. Recent/Upcoming Books and Training 1) HTML5 Canvas and CSS3 Graphics (2013) 2) jQuery, CSS3, and HTML5 for Mobile (2013) 3) HTML5 Pocket Primer (2013) 4) jQuery Pocket Primer (2013) 5) HTML5 Mobile Pocket Primer (2014) 6) D3 Pocket Primer (2015) 7) Python Pocket Primer (2015) 8) SVG Pocket Primer (2016) 9) CSS3 Pocket Primer (2016) 10) Angular 2 Pocket Primer (2016)