SlideShare a Scribd company logo
1 of 39
Functional Reactive 
Programming in JS 
Mario Zupan 
@mzupzup 
Stefan Mayer 
@stefanmayer13
Who are we? 
@stefanmayer13 @mzupzup 
2
Motivation 
■ Technology stack re-evaluation 
■ Lessons learned 
■ Functional Programming 
■ QCon NYC 
[1] 
3
What is Functional Reactive 
Programming? 
4
Reactive Manifesto 
[2] 
5
Reactive Manifesto 
? ? 
? ? [2] 
6
Functional Programming 
■ Evaluation of mathematical functions 
■ Avoid mutable state 
■ Referential transparency 
■ Avoid side-effects 
■ Reusable functions over reusable object 
■ Function composition over object 
composition 
[1] 
7
Functional Programming 
■ map 
■ filter 
■ mergeAll 
■ reduce 
■ zip 
[3] 
[4] 8
var data = [1, 2, 3, 4, 5]; 
var numbers = data.map(function (nr) { 
return nr + 1; 
}); 
// numbers = [2, 3, 4, 5, 6] 
9
var data = [1, 2, 3, 4, 5, 6, 7]; 
var numbers = data.filter(function (nr) { 
return nr % 2 === 0; 
}); 
// numbers = [2, 4, 6] 
10
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] 
11
var data = [[1, 2], [3, 4], 5, [6], 7, 8]; 
var numbers = data.mergeAll(); 
// numbers = [1, 2, 3, 4, 5, 6, 7, 8] 
12
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] 
13
var data = [1, 2, 3, 4]; 
var sum = data.reduce(function(acc, value) { 
return acc + value; 
}); 
// sum = 10 
14
var data = [5, 7, 3, 4]; 
var min = data.reduce(function(acc, value) { 
return acc < value ? acc : value; 
}); 
// min = 3 
15
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]] 
16
Reactive Programming 
■ Asynchronous data streams 
■ Everything is a stream 
● click events 
● user inputs 
● data from a server 
■ streams rock! 
17
Reactive Programming 
[5] 
18
F + R + P 
■ Powerful composition and aggregation of 
streams 
■ Good fit for concurrent and event-driven 
systems 
■ Declarative 
■ Easy to test 
[6] 
19
Observables 
■ Stream of data over time 
■ Hot vs cold observables 
■ Asynchronous 
■ Lazy 
■ queryable, bufferable, pausable… 
■ more than 120 operations 
[7] 
20
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}); 
21
Observable Basics 
var range = Rx.Observable.range(1, 3); // 1, 2, 3 
var range = range.subscribe( 
function(value) {}, 
function(error) {}, 
function() {} 
); 
optional 
22
Observable Basics 
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>" 
23
Cold Observables 
[8] 
24
Hot Observables 
[9] 
25
Autocomplete 
● Multiple requests 
● Async results 
● Race conditions 
● State 
● ... 
[10] 
26
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) 
27
Autocomplete 2/2 
.distinctUntilChanged() // only if changes 
.flatMapLatest(doAsyncSearch() // do async search on server 
.retry(3)) 
.takeUntil(cancelStream) // cancel stream 
.subscribe( 
function (data) { // do UI stuff }, 
function (error) { // do error handling } 
); 
28
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'); 
[11] 
29
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 
}); [11] 
30
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() 31
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 
[12] 
32
Framework Bridges 
■ AngularJS 
■ ReactJS 
■ jQuery 
■ ExtJS 
■ NodeJS 
■ Backbone 
■ ... 
33
Companies using Rx in Production 
[13] 
34
Alternatives to RxJS 
■ BaconJS 
■ Kefir 
■ (Elm) 
35
Conclusion 
■ There is a learning curve 
■ Great abstraction for async & events 
■ Improves 
● Readability 
● Reusability 
● Scalability 
■ Both on the front- and backend 
36
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/ 
37
Image references 
■ 1 - http://www.ylies.fr/ 
■ 2 - http://www.reactivemanifesto.org 
■ 3 - http://reactivex.io/ 
■ 4 - https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/ 
■ 5 - http://buildstuff14.sched.org/event/9ead0e99b3c1c0edddec6c7c8d526125#.VHEgq5PF-kQ 
■ 6 - http://www.cclscorp.com 
■ 7 - http://www.pharmmd.com/ 
■ 8 - http://blogs.msdn.com/ 
■ 9 - http://blogs.msdn.com/ 
■ 10 - https://www.google.at 
■ 11 - http://dockphp.com/ 
■ 12 - http://www.thechrisyates.com/ 
■ 13 - http://www.reactivex.io 
■ 14 - http://www.quickmeme.com/ 
38
Thank you 
@stefanmayer13 
@mzupzup 
[14] 
39

More Related Content

What's hot

Spring Batch Avance
Spring Batch AvanceSpring Batch Avance
Spring Batch Avance
Olivier BAZOUD
 

What's hot (20)

OPcache の最適化器の今
OPcache の最適化器の今OPcache の最適化器の今
OPcache の最適化器の今
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
 
Rust
RustRust
Rust
 
Spring batch introduction
Spring batch introductionSpring batch introduction
Spring batch introduction
 
[수정본] 우아한 객체지향
[수정본] 우아한 객체지향[수정본] 우아한 객체지향
[수정본] 우아한 객체지향
 
Redux Saga - Under the hood
Redux Saga - Under the hoodRedux Saga - Under the hood
Redux Saga - Under the hood
 
MVVM with SwiftUI and Combine
MVVM with SwiftUI and CombineMVVM with SwiftUI and Combine
MVVM with SwiftUI and Combine
 
Spring Batch Avance
Spring Batch AvanceSpring Batch Avance
Spring Batch Avance
 
WTF is Reactive Programming
WTF is Reactive ProgrammingWTF is Reactive Programming
WTF is Reactive Programming
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Java nio ( new io )
Java nio ( new io )Java nio ( new io )
Java nio ( new io )
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Top Ten SE Concepts V11.1 Jp
Top Ten SE Concepts V11.1 JpTop Ten SE Concepts V11.1 Jp
Top Ten SE Concepts V11.1 Jp
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
 
Vulkan 1.1 Reference Guide
Vulkan 1.1 Reference GuideVulkan 1.1 Reference Guide
Vulkan 1.1 Reference Guide
 

Viewers also liked

Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高
 
System webpack-jspm
System webpack-jspmSystem webpack-jspm
System webpack-jspm
Jesse Warden
 

Viewers also liked (16)

NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
Functional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwiftFunctional Reactive Programming With RxSwift
Functional Reactive Programming With RxSwift
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
Angular2 ecosystem
Angular2 ecosystemAngular2 ecosystem
Angular2 ecosystem
 
System webpack-jspm
System webpack-jspmSystem webpack-jspm
System webpack-jspm
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409
 
맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 맛만 보자 액터 모델이란
맛만 보자 액터 모델이란
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 

Similar to Functional Reactive Programming with RxJS

オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
timotheeg
 

Similar to Functional Reactive Programming with RxJS (20)

Functional Reactive Programming in JavaScript
Functional Reactive Programming in JavaScriptFunctional Reactive Programming in JavaScript
Functional Reactive Programming in JavaScript
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
SF Big Analytics 20191112: How to performance-tune Spark applications in larg...
SF Big Analytics 20191112: How to performance-tune Spark applications in larg...SF Big Analytics 20191112: How to performance-tune Spark applications in larg...
SF Big Analytics 20191112: How to performance-tune Spark applications in larg...
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
How to practice functional programming in react
How to practice functional programming in reactHow to practice functional programming in react
How to practice functional programming in react
 
ECMA5 and ES6 Promises
ECMA5 and ES6 PromisesECMA5 and ES6 Promises
ECMA5 and ES6 Promises
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF Observability
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
JS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless BebopJS Fest 2019. Anjana Vakil. Serverless Bebop
JS Fest 2019. Anjana Vakil. Serverless Bebop
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

Functional Reactive Programming with RxJS

  • 1. Functional Reactive Programming in JS Mario Zupan @mzupzup Stefan Mayer @stefanmayer13
  • 2. Who are we? @stefanmayer13 @mzupzup 2
  • 3. Motivation ■ Technology stack re-evaluation ■ Lessons learned ■ Functional Programming ■ QCon NYC [1] 3
  • 4. What is Functional Reactive Programming? 4
  • 6. Reactive Manifesto ? ? ? ? [2] 6
  • 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 [1] 7
  • 8. Functional Programming ■ map ■ filter ■ mergeAll ■ reduce ■ zip [3] [4] 8
  • 9. var data = [1, 2, 3, 4, 5]; var numbers = data.map(function (nr) { return nr + 1; }); // numbers = [2, 3, 4, 5, 6] 9
  • 10. var data = [1, 2, 3, 4, 5, 6, 7]; var numbers = data.filter(function (nr) { return nr % 2 === 0; }); // numbers = [2, 4, 6] 10
  • 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] 11
  • 12. var data = [[1, 2], [3, 4], 5, [6], 7, 8]; var numbers = data.mergeAll(); // numbers = [1, 2, 3, 4, 5, 6, 7, 8] 12
  • 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] 13
  • 14. var data = [1, 2, 3, 4]; var sum = data.reduce(function(acc, value) { return acc + value; }); // sum = 10 14
  • 15. var data = [5, 7, 3, 4]; var min = data.reduce(function(acc, value) { return acc < value ? acc : value; }); // min = 3 15
  • 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]] 16
  • 17. Reactive Programming ■ Asynchronous data streams ■ Everything is a stream ● click events ● user inputs ● data from a server ■ streams rock! 17
  • 19. F + R + P ■ Powerful composition and aggregation of streams ■ Good fit for concurrent and event-driven systems ■ Declarative ■ Easy to test [6] 19
  • 20. Observables ■ Stream of data over time ■ Hot vs cold observables ■ Asynchronous ■ Lazy ■ queryable, bufferable, pausable… ■ more than 120 operations [7] 20
  • 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}); 21
  • 22. Observable Basics var range = Rx.Observable.range(1, 3); // 1, 2, 3 var range = range.subscribe( function(value) {}, function(error) {}, function() {} ); optional 22
  • 23. Observable Basics 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>" 23
  • 26. Autocomplete ● Multiple requests ● Async results ● Race conditions ● State ● ... [10] 26
  • 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) 27
  • 28. Autocomplete 2/2 .distinctUntilChanged() // only if changes .flatMapLatest(doAsyncSearch() // do async search on server .retry(3)) .takeUntil(cancelStream) // cancel stream .subscribe( function (data) { // do UI stuff }, function (error) { // do error handling } ); 28
  • 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'); [11] 29
  • 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 }); [11] 30
  • 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() 31
  • 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 [12] 32
  • 33. Framework Bridges ■ AngularJS ■ ReactJS ■ jQuery ■ ExtJS ■ NodeJS ■ Backbone ■ ... 33
  • 34. Companies using Rx in Production [13] 34
  • 35. Alternatives to RxJS ■ BaconJS ■ Kefir ■ (Elm) 35
  • 36. Conclusion ■ There is a learning curve ■ Great abstraction for async & events ■ Improves ● Readability ● Reusability ● Scalability ■ Both on the front- and backend 36
  • 37. 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/ 37
  • 38. Image references ■ 1 - http://www.ylies.fr/ ■ 2 - http://www.reactivemanifesto.org ■ 3 - http://reactivex.io/ ■ 4 - https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/ ■ 5 - http://buildstuff14.sched.org/event/9ead0e99b3c1c0edddec6c7c8d526125#.VHEgq5PF-kQ ■ 6 - http://www.cclscorp.com ■ 7 - http://www.pharmmd.com/ ■ 8 - http://blogs.msdn.com/ ■ 9 - http://blogs.msdn.com/ ■ 10 - https://www.google.at ■ 11 - http://dockphp.com/ ■ 12 - http://www.thechrisyates.com/ ■ 13 - http://www.reactivex.io ■ 14 - http://www.quickmeme.com/ 38
  • 39. Thank you @stefanmayer13 @mzupzup [14] 39

Editor's Notes

  1. Bevor functional reactive programming -> functional Im Gegensatz zu imperativ wird mit mathematischen funktionen gearbeitet. Instruktionen Mapping Input -> Output immer gleich unabhängig vom ausführungszeitpunkt Immutable
  2. FP umfasst großes Gebiet
  3. ----- Meeting Notes (27/11/14 18:27) ----- Transformieren
  4. Numbers Attribut
  5. Bisher alle Operationen nur auf 1 Element der Collection
  6. Schluss
  7. Probleme von suggest erklären: Bei Eingaben zuviele requests race conditions by async (späterer request kann früher zurückkommen)
  8. Probleme von suggest erklären: zuviele requests, statefull, race conditions by async
  9. pausable nur auf hot observables