SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介
Takaaki Hirano
 

La actualidad más candente (20)

【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Debug Information And Where They Come From
Debug Information And Where They Come FromDebug Information And Where They Come From
Debug Information And Where They Come From
 
x86とコンテキストスイッチ
x86とコンテキストスイッチx86とコンテキストスイッチ
x86とコンテキストスイッチ
 
190119 unreal engine c++ 입문 및 팁
190119 unreal engine c++ 입문 및 팁190119 unreal engine c++ 입문 및 팁
190119 unreal engine c++ 입문 및 팁
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Effective Modern C++
Effective Modern C++Effective Modern C++
Effective Modern C++
 
Docker 로 Linux 없이 Linux 환경에서 개발하기
Docker 로 Linux 없이 Linux 환경에서 개발하기Docker 로 Linux 없이 Linux 환경에서 개발하기
Docker 로 Linux 없이 Linux 환경에서 개발하기
 
Transferring Changes Between Perforce Servers
Transferring Changes Between Perforce ServersTransferring Changes Between Perforce Servers
Transferring Changes Between Perforce Servers
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
Nsx t api-automation_202103
Nsx t api-automation_202103Nsx t api-automation_202103
Nsx t api-automation_202103
 
Unity遊戲程式設計 - 2D移動與碰撞處理II
Unity遊戲程式設計 - 2D移動與碰撞處理IIUnity遊戲程式設計 - 2D移動與碰撞處理II
Unity遊戲程式設計 - 2D移動與碰撞處理II
 
Important React Hooks
Important React HooksImportant React Hooks
Important React Hooks
 
Rust Primer
Rust PrimerRust Primer
Rust Primer
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
 
プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介プログラミング言語のマスコットとか紹介
プログラミング言語のマスコットとか紹介
 
[2019] 언리얼 엔진을 통해 살펴보는 리플렉션과 가비지 컬렉션
[2019] 언리얼 엔진을 통해 살펴보는 리플렉션과 가비지 컬렉션[2019] 언리얼 엔진을 통해 살펴보는 리플렉션과 가비지 컬렉션
[2019] 언리얼 엔진을 통해 살펴보는 리플렉션과 가비지 컬렉션
 
중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직중앙 서버 없는 게임 로직
중앙 서버 없는 게임 로직
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 

Destacado

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

Destacado (15)

[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 a 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 a 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
 

Último

+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@
 
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
 

Último (20)

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 Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
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...
 
+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...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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)
 
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
 
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
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

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

Notas del editor

  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