SlideShare a Scribd company logo
Functional Reactive
Programming in JS
Mario Zupan
@mzupzup
Stefan Mayer
@stefanmayer13
Who are we?
@stefanmayer13 @mzupzup
Motivation
■ Technology stack re-evaluation
■ Lessons learned
■ Functional Programming
■ QCon NYC
What is Functional Reactive
Programming?
Reactive Manifesto
Reactive Manifesto
? ?
? ?
Functional Programming
■ Evaluation of mathematical functions
■ Avoid mutable state
■ Referential transparency
■ Avoid side-effects
■ Reusable functions over reusable object
■ Function composition over object
composition
Functional Programming
■ map
■ filter
■ mergeAll
■ reduce
■ zip
var data = [1, 2, 3, 4, 5];
var numbers = data.map(function (nr) {
return nr + 1;
});
//numbers = [2, 3, 4, 5, 6]
var data = [1, 2, 3, 4, 5, 6, 7];
var numbers = data.filter(function (nr) {
return nr % 2 === 0;
});
// numbers = [2, 4, 6]
var data = [1, 2, 3, 4, 5, 6, 7];
var numbers = data.map(function (nr) {
return nr + 1;
}).filter(function (nr) {
return nr % 2 === 0;
});
// numbers = [2, 4, 6, 8]
var data = [[1, 2], [3, 4], 5, [6], 7, 8];
var numbers = data.mergeAll();
// numbers = [1, 2, 3, 4, 5, 6, 7, 8]
var data = [{
numbers: [1, 2]
}, {
numbers: [3, 4]
};
var numbersFlatMap = data.flatMap(function (object) {
return object.numbers;
});
// numbersMap = [[1, 2], [3, 4]]
// numbersFlatMap = [1, 2, 3, 4]
var data = [1, 2, 3, 4];
var sum = data.reduce(function(acc, value) {
return acc + value;
});
// sum = 10
var data = [5, 7, 3, 4];
var min = data.reduce(function(acc, value) {
return acc < value ? acc : value;
});
// min = 3
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array = Array.zip(array1, array2,
function(left, right) {
return [left, right];
});
// array = [[1, 4], [2, 5], [3, 6]]
Reactive Programming
■ Asynchronous data streams
■ Everything is a stream
● click events
● user inputs
● data from a server
■ streams rock!
Reactive Programming
F + R + P
■ Powerful Composition and Aggregation of
streams
■ Good fit for concurrent and event-driven
systems
■ Declarative
■ Easy to test
Observables
■ Stream of data over time
■ Hot vs Cold Observables
■ Asynchronous
■ Lazy
■ queryable, bufferable, pausable…
■ more than 120 operations
Observable Creation
Rx.Observable.fromArray([1, 2, 3]);
Rx.Observable.fromEvent(input, 'click');
Rx.Observable.fromEvent(eventEmitter, 'data', fn);
Rx.Observable.fromCallback(fs.exists);
Rx.Observable.fromNodeCallback(fs.exists);
Rx.Observable.fromPromise(somePromise);
Rx.Observable.fromIterable(function*() {yield 20});
var range = Rx.Observable.range(1, 3); // 1, 2, 3
var range = range.subscribe(
function(value) {},
function(error) {},
function() {}
);
Observable Basics
optional
var range = Rx.Observable.range(1, 10) // 1, 2, 3 ...
.filter(function(value) { return value % 2 === 0; })
.map(function(value) { return "<span>" + value + "</span>"; })
.takeLast(1);
var subscription = range.subscribe(
function(value) { console.log("last even value: " + value); });
// "last even value: <span>10</span>"
Observable Basics
Cold Observables
Hot Observables
Autocomplete
● Multiple requests
● Async results
● Race conditions
● State
● ...
Autocomplete 1/2
var keyup = Rx.Observable.fromEvent(input, 'keyup')
.map(function (e) {
return e.target.value; // map to text
})
.filter(function (input) {
return input.length > 2; // filter relevant values
})
.debounce(250)
.distinctUntilChanged() // only if changes
.flatMapLatest(doAsyncSearch() // do async search on server
.retry(3))
.takeUntil(cancelStream) // chancel stream
.subscribe(
function (data) { // do UI stuff },
function (error) { // do error handling }
);
Autocomplete 2/2
Drag & Drop 1/2
var mousedown = Rx.Observable.fromEvent(dragTarget, 'mousedown');
var mousemove = Rx.Observable.fromEvent(document, 'mousemove');
var mouseup = Rx.Observable.fromEvent(dragTarget, 'mouseup');
mousedown.flatMap(function (md) {
// get starting coordinates
var startX = md.offsetX, startY = md.offsetY;
return mousemove.map(function (mm) {
// return the mouse distance from start
return {left: mm.clientX - startX, top: mm.clientY - startY };
}).takeUntil(mouseup);
}).subscribe(function (pos) {
// do UI stuff
});
Some Cool Stuff on Observables
.bufferWithTime(500)
.pausable(pauser), .pausableBuffered(..)
.repeat(3)
.skip(1), skipUntilWithTime(..)
.do() // for side-effects like logging
.onErrorResumeNext(second) // resume with other obs
.window() // project into windows
.timestamp() // add time for each value
.delay()
RxJS
Supported
■ IE6+
■ Chrome 4+
■ FireFox 1+
■ Node.js v0.4+
Size (minified & gzipped):
■ all - 23,1k
■ lite - 13,5k
■ compat - 12,5k
■ ES5 core - 12k
Framework Bridges
■ AngularJS
■ ReactJS
■ jQuery
■ ExtJS
■ NodeJS
■ Backbone
■ ...
Companies using Rx in Production
Alternatives to RxJS
■ BaconJS
■ Kefir
■ (Elm)
Conclusion
■ There is a learning curve
■ Great abstraction for async & events
■ Improves
● Readability
● Reusability
● Scalability
■ Both on the front- and backend
Image references
■ KefirJS - https://camo.githubusercontent.com/
■ BaconJS - http://baconjs.github.io
■ data stream - http://www.pharmmd.com/
■ Elm - http://elm-lang.org
■ Browsers - http://www.thechrisyates.com/
■ websocket logo - http://blog.appharbor.com/
■ drag n drop - http://dockphp.com/
■ f(x) - http://www.ylies.fr/
■ qcon - https://qconsf.com/
■ check sign - http://www.cclscorp.com
■ map - http://reactivex.io/
■ reactivex logo - http://reactivex.io
■ chuck norris - http://www.quickmeme.com/
■ sencha - http://www.sencha.com/
■ reactive companies - http://www.reactivex.io
■ filter reactive - https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/
■ node logo - http://calebmadrigal.com/
■ extjs - http://marceloagustini.files.wordpress.com/
■ hot observables - http://blogs.msdn.com/
■ cold observables - http://blogs.msdn.com/
■ backbone - http://2.bp.blogspot.com/
■ reactjs - http://moduscreate.com/
■ angular - http://www.w3schools.com/
■ reactive diagram observables - http://buildstuff14.sched.org/event/9ead0e99b3c1c0edddec6c7c8d526125#.VHEgq5PF-kQ
■ reactivemanifesto - http://www.reactivemanifesto.org
Learning RxJS
■ RxKoans
○ https://github.com/Reactive-Extensions/RxJSKoans
■ learnRx
○ https://github.com/jhusain/learnrx
■ The Introduction to Reactive Programming you've been
missing
○ https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
■ rxMarbles
○ http://rxmarbles.com/
Thank you
@stefanmayer13
@mzupzup

More Related Content

PPTX
Functional Reactive Programming with RxJS
PPTX
Luis Atencio on RxJS
PDF
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
PDF
rx.js make async programming simpler
PDF
RxJS - The Reactive extensions for JavaScript
PDF
RxJS 5 in Depth
PDF
RxJS Evolved
PDF
Functional Reactive Programming
Functional Reactive Programming with RxJS
Luis Atencio on RxJS
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
rx.js make async programming simpler
RxJS - The Reactive extensions for JavaScript
RxJS 5 in Depth
RxJS Evolved
Functional Reactive Programming

What's hot (20)

PDF
Add Some Fun to Your Functional Programming With RXJS
PDF
Cascadia.js: Don't Cross the Streams
PPTX
Storm is coming
KEY
W3C HTML5 KIG-How to write low garbage real-time javascript
PDF
The power of streams in node js
PDF
What they don't tell you about JavaScript
PDF
Compose Async with RxJS
PPTX
IOT Firmware: Best Pratices
PDF
Sujet bac info 2013 g1, g2 et g3 avec correction
PDF
RxJS101 - What you need to know to get started with RxJS tomorrow
ODP
Event Loop in Javascript
PPT
Tilting Google Maps and MissileLauncher
PDF
10 chapter6 heaps_priority_queues
PPTX
HAB Software Woes
PDF
Bristol 2009 q1_wright_steve
PDF
Cocoa勉強会23-識別情報の変換〜文字エンコードとデータタイプ
PDF
Functional Reactive Programming / Compositional Event Systems
ODP
Daniel Sikar: Hadoop MapReduce - 06/09/2010
PDF
Ganga: an interface to the LHC computing grid
PPTX
Synapse india dotnet development overloading operater part 4
Add Some Fun to Your Functional Programming With RXJS
Cascadia.js: Don't Cross the Streams
Storm is coming
W3C HTML5 KIG-How to write low garbage real-time javascript
The power of streams in node js
What they don't tell you about JavaScript
Compose Async with RxJS
IOT Firmware: Best Pratices
Sujet bac info 2013 g1, g2 et g3 avec correction
RxJS101 - What you need to know to get started with RxJS tomorrow
Event Loop in Javascript
Tilting Google Maps and MissileLauncher
10 chapter6 heaps_priority_queues
HAB Software Woes
Bristol 2009 q1_wright_steve
Cocoa勉強会23-識別情報の変換〜文字エンコードとデータタイプ
Functional Reactive Programming / Compositional Event Systems
Daniel Sikar: Hadoop MapReduce - 06/09/2010
Ganga: an interface to the LHC computing grid
Synapse india dotnet development overloading operater part 4
Ad

Viewers also liked (7)

PDF
Running Containerized Node.js Services on AWS Elastic Beanstalk
PDF
Functional Programming Patterns for the Pragmatic Programmer
PDF
Quality and Software Design Patterns
PDF
Functional Programming Principles & Patterns
PPT
Software design methodologies
PDF
Functional Programming Patterns (NDC London 2014)
PPTX
Running Containerized Node.js Services on AWS Elastic Beanstalk
Functional Programming Patterns for the Pragmatic Programmer
Quality and Software Design Patterns
Functional Programming Principles & Patterns
Software design methodologies
Functional Programming Patterns (NDC London 2014)
Ad

Similar to Functional Reactive Programming in JavaScript (20)

PDF
[DevDay 2019] Reactive Programming with JavaScript - By Pham Nguyen Duc, Web ...
PPTX
Functional Reactive Programming (FRP): Working with RxJS
PDF
My Gentle Introduction to RxJS
PPTX
Functional reactive programming
PPTX
RxJS and Reactive Programming - Modern Web UI - May 2015
PDF
Reactive programming and RxJS
PDF
RxJS - The Reactive Extensions for JavaScript
PPTX
Intro to RxJS
PPTX
Rxjs swetugg
PDF
Reactive programming with RxJS - Taiwan
PPTX
PPTX
Solve it Differently with Reactive Programming
PDF
Rxjs kyivjs 2015
PDF
Predictable reactive state management - ngrx
PDF
Reactive programming with RxJS - ByteConf 2018
PDF
Functional Reactive Programming in Clojurescript
ODP
Appstate
PPTX
Reactive programming
PPTX
Reactive programming with rx java
PDF
DZone_RC_RxJS
[DevDay 2019] Reactive Programming with JavaScript - By Pham Nguyen Duc, Web ...
Functional Reactive Programming (FRP): Working with RxJS
My Gentle Introduction to RxJS
Functional reactive programming
RxJS and Reactive Programming - Modern Web UI - May 2015
Reactive programming and RxJS
RxJS - The Reactive Extensions for JavaScript
Intro to RxJS
Rxjs swetugg
Reactive programming with RxJS - Taiwan
Solve it Differently with Reactive Programming
Rxjs kyivjs 2015
Predictable reactive state management - ngrx
Reactive programming with RxJS - ByteConf 2018
Functional Reactive Programming in Clojurescript
Appstate
Reactive programming
Reactive programming with rx java
DZone_RC_RxJS

Recently uploaded (20)

PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPT
Introduction Database Management System for Course Database
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
AIRLINE PRICE API | FLIGHT API COST |
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Transform Your Business with a Software ERP System
The Role of Automation and AI in EHS Management for Data Centers.pdf
Softaken Excel to vCard Converter Software.pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
How to Choose the Right IT Partner for Your Business in Malaysia
Odoo POS Development Services by CandidRoot Solutions
Upgrade and Innovation Strategies for SAP ERP Customers
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
How to Migrate SBCGlobal Email to Yahoo Easily
Introduction Database Management System for Course Database
ManageIQ - Sprint 268 Review - Slide Deck
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Which alternative to Crystal Reports is best for small or large businesses.pdf
Best Practices for Rolling Out Competency Management Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
AIRLINE PRICE API | FLIGHT API COST |
2025 Textile ERP Trends: SAP, Odoo & Oracle
Transform Your Business with a Software ERP System

Functional Reactive Programming in JavaScript

  • 1. Functional Reactive Programming in JS Mario Zupan @mzupzup Stefan Mayer @stefanmayer13
  • 3. Motivation ■ Technology stack re-evaluation ■ Lessons learned ■ Functional Programming ■ QCon NYC
  • 4. What is Functional Reactive Programming?
  • 7. Functional Programming ■ Evaluation of mathematical functions ■ Avoid mutable state ■ Referential transparency ■ Avoid side-effects ■ Reusable functions over reusable object ■ Function composition over object composition
  • 8. Functional Programming ■ map ■ filter ■ mergeAll ■ reduce ■ zip
  • 9. var data = [1, 2, 3, 4, 5]; var numbers = data.map(function (nr) { return nr + 1; }); //numbers = [2, 3, 4, 5, 6]
  • 10. var data = [1, 2, 3, 4, 5, 6, 7]; var numbers = data.filter(function (nr) { return nr % 2 === 0; }); // numbers = [2, 4, 6]
  • 11. var data = [1, 2, 3, 4, 5, 6, 7]; var numbers = data.map(function (nr) { return nr + 1; }).filter(function (nr) { return nr % 2 === 0; }); // numbers = [2, 4, 6, 8]
  • 12. var data = [[1, 2], [3, 4], 5, [6], 7, 8]; var numbers = data.mergeAll(); // numbers = [1, 2, 3, 4, 5, 6, 7, 8]
  • 13. var data = [{ numbers: [1, 2] }, { numbers: [3, 4] }; var numbersFlatMap = data.flatMap(function (object) { return object.numbers; }); // numbersMap = [[1, 2], [3, 4]] // numbersFlatMap = [1, 2, 3, 4]
  • 14. var data = [1, 2, 3, 4]; var sum = data.reduce(function(acc, value) { return acc + value; }); // sum = 10
  • 15. var data = [5, 7, 3, 4]; var min = data.reduce(function(acc, value) { return acc < value ? acc : value; }); // min = 3
  • 16. var array1 = [1, 2, 3]; var array2 = [4, 5, 6]; var array = Array.zip(array1, array2, function(left, right) { return [left, right]; }); // array = [[1, 4], [2, 5], [3, 6]]
  • 17. Reactive Programming ■ Asynchronous data streams ■ Everything is a stream ● click events ● user inputs ● data from a server ■ streams rock!
  • 19. F + R + P ■ Powerful Composition and Aggregation of streams ■ Good fit for concurrent and event-driven systems ■ Declarative ■ Easy to test
  • 20. Observables ■ Stream of data over time ■ Hot vs Cold Observables ■ Asynchronous ■ Lazy ■ queryable, bufferable, pausable… ■ more than 120 operations
  • 21. Observable Creation Rx.Observable.fromArray([1, 2, 3]); Rx.Observable.fromEvent(input, 'click'); Rx.Observable.fromEvent(eventEmitter, 'data', fn); Rx.Observable.fromCallback(fs.exists); Rx.Observable.fromNodeCallback(fs.exists); Rx.Observable.fromPromise(somePromise); Rx.Observable.fromIterable(function*() {yield 20});
  • 22. var range = Rx.Observable.range(1, 3); // 1, 2, 3 var range = range.subscribe( function(value) {}, function(error) {}, function() {} ); Observable Basics optional
  • 23. var range = Rx.Observable.range(1, 10) // 1, 2, 3 ... .filter(function(value) { return value % 2 === 0; }) .map(function(value) { return "<span>" + value + "</span>"; }) .takeLast(1); var subscription = range.subscribe( function(value) { console.log("last even value: " + value); }); // "last even value: <span>10</span>" Observable Basics
  • 26. Autocomplete ● Multiple requests ● Async results ● Race conditions ● State ● ...
  • 27. Autocomplete 1/2 var keyup = Rx.Observable.fromEvent(input, 'keyup') .map(function (e) { return e.target.value; // map to text }) .filter(function (input) { return input.length > 2; // filter relevant values }) .debounce(250)
  • 28. .distinctUntilChanged() // only if changes .flatMapLatest(doAsyncSearch() // do async search on server .retry(3)) .takeUntil(cancelStream) // chancel stream .subscribe( function (data) { // do UI stuff }, function (error) { // do error handling } ); Autocomplete 2/2
  • 29. Drag & Drop 1/2 var mousedown = Rx.Observable.fromEvent(dragTarget, 'mousedown'); var mousemove = Rx.Observable.fromEvent(document, 'mousemove'); var mouseup = Rx.Observable.fromEvent(dragTarget, 'mouseup');
  • 30. mousedown.flatMap(function (md) { // get starting coordinates var startX = md.offsetX, startY = md.offsetY; return mousemove.map(function (mm) { // return the mouse distance from start return {left: mm.clientX - startX, top: mm.clientY - startY }; }).takeUntil(mouseup); }).subscribe(function (pos) { // do UI stuff });
  • 31. Some Cool Stuff on Observables .bufferWithTime(500) .pausable(pauser), .pausableBuffered(..) .repeat(3) .skip(1), skipUntilWithTime(..) .do() // for side-effects like logging .onErrorResumeNext(second) // resume with other obs .window() // project into windows .timestamp() // add time for each value .delay()
  • 32. RxJS Supported ■ IE6+ ■ Chrome 4+ ■ FireFox 1+ ■ Node.js v0.4+ Size (minified & gzipped): ■ all - 23,1k ■ lite - 13,5k ■ compat - 12,5k ■ ES5 core - 12k
  • 33. Framework Bridges ■ AngularJS ■ ReactJS ■ jQuery ■ ExtJS ■ NodeJS ■ Backbone ■ ...
  • 34. Companies using Rx in Production
  • 35. Alternatives to RxJS ■ BaconJS ■ Kefir ■ (Elm)
  • 36. Conclusion ■ There is a learning curve ■ Great abstraction for async & events ■ Improves ● Readability ● Reusability ● Scalability ■ Both on the front- and backend
  • 37. Image references ■ KefirJS - https://camo.githubusercontent.com/ ■ BaconJS - http://baconjs.github.io ■ data stream - http://www.pharmmd.com/ ■ Elm - http://elm-lang.org ■ Browsers - http://www.thechrisyates.com/ ■ websocket logo - http://blog.appharbor.com/ ■ drag n drop - http://dockphp.com/ ■ f(x) - http://www.ylies.fr/ ■ qcon - https://qconsf.com/ ■ check sign - http://www.cclscorp.com ■ map - http://reactivex.io/ ■ reactivex logo - http://reactivex.io ■ chuck norris - http://www.quickmeme.com/ ■ sencha - http://www.sencha.com/ ■ reactive companies - http://www.reactivex.io ■ filter reactive - https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/ ■ node logo - http://calebmadrigal.com/ ■ extjs - http://marceloagustini.files.wordpress.com/ ■ hot observables - http://blogs.msdn.com/ ■ cold observables - http://blogs.msdn.com/ ■ backbone - http://2.bp.blogspot.com/ ■ reactjs - http://moduscreate.com/ ■ angular - http://www.w3schools.com/ ■ reactive diagram observables - http://buildstuff14.sched.org/event/9ead0e99b3c1c0edddec6c7c8d526125#.VHEgq5PF-kQ ■ reactivemanifesto - http://www.reactivemanifesto.org
  • 38. Learning RxJS ■ RxKoans ○ https://github.com/Reactive-Extensions/RxJSKoans ■ learnRx ○ https://github.com/jhusain/learnrx ■ The Introduction to Reactive Programming you've been missing ○ https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 ■ rxMarbles ○ http://rxmarbles.com/