SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)Scott Wlaschin
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureOdoo
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented ProgrammingScott Wlaschin
 
WebAssembly: In a Nutshell
WebAssembly: In a NutshellWebAssembly: In a Nutshell
WebAssembly: In a NutshellRangHo Lee
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Wangeun Lee
 
Gradleどうでしょう
GradleどうでしょうGradleどうでしょう
GradleどうでしょうTakuma Watabiki
 
CSS Paged Media - A review of tools and techniques
CSS Paged Media - A review of tools and techniquesCSS Paged Media - A review of tools and techniques
CSS Paged Media - A review of tools and techniquesAndreas Jung
 
Programming Languages: comparison, history, future
Programming Languages: comparison, history, futureProgramming Languages: comparison, history, future
Programming Languages: comparison, history, futureTimur Shemsedinov
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOdoo
 
Requêtes HTTP synchrones et asynchrones
Requêtes HTTPsynchrones et asynchronesRequêtes HTTPsynchrones et asynchrones
Requêtes HTTP synchrones et asynchronesAbdoulaye Dieng
 
Primeiros passos com a API do Zabbix
Primeiros passos com a API do ZabbixPrimeiros passos com a API do Zabbix
Primeiros passos com a API do ZabbixJanssen Lima
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applicationsSergi Mansilla
 

Tendances (20)

The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)The Power Of Composition (DotNext 2019)
The Power Of Composition (DotNext 2019)
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
WebAssembly: In a Nutshell
WebAssembly: In a NutshellWebAssembly: In a Nutshell
WebAssembly: In a Nutshell
 
Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계Spring integration을 통해_살펴본_메시징_세계
Spring integration을 통해_살펴본_메시징_세계
 
Gradleどうでしょう
GradleどうでしょうGradleどうでしょう
Gradleどうでしょう
 
CSS Paged Media - A review of tools and techniques
CSS Paged Media - A review of tools and techniquesCSS Paged Media - A review of tools and techniques
CSS Paged Media - A review of tools and techniques
 
Programming Languages: comparison, history, future
Programming Languages: comparison, history, futureProgramming Languages: comparison, history, future
Programming Languages: comparison, history, future
 
Express JS
Express JSExpress JS
Express JS
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Requêtes HTTP synchrones et asynchrones
Requêtes HTTPsynchrones et asynchronesRequêtes HTTPsynchrones et asynchrones
Requêtes HTTP synchrones et asynchrones
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Primeiros passos com a API do Zabbix
Primeiros passos com a API do ZabbixPrimeiros passos com a API do Zabbix
Primeiros passos com a API do Zabbix
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 

En vedette

NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기
NDC14 - Rx와 Functional Reactive Programming으로 고성능 서버 만들기Jong Wook Kim
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍NAVER D2
 
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 Streamsmattpodwysocki
 
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 2015Ben Lesh
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - Polymer혁신적인 웹컴포넌트 라이브러리 - Polymer
혁신적인 웹컴포넌트 라이브러리 - PolymerJae Sung Park
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
System webpack-jspm
System webpack-jspmSystem webpack-jspm
System webpack-jspmJesse Warden
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
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 - 20150409Minko3D
 
맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 jbugkorea
 
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 awesomeAndrew Hull
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기Wanbok Choi
 

En vedette (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 시작하기
 

Similaire à Functional Reactive Programming with RxJS

Functional Reactive Programming in JavaScript
Functional Reactive Programming in JavaScriptFunctional Reactive Programming in JavaScript
Functional Reactive Programming in JavaScriptzupzup.org
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)Takayuki Goto
 
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...Chester Chen
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
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 reactNetta Bondy
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?jonbodner
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityBrendan Gregg
 
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 2015Michiel Borkent
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35Bilal Ahmed
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersRick Beerendonk
 
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 AnalysisFastly
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6WebF
 
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 BebopJSFestUA
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]RxJava applied [JavaDay Kyiv 2016]
RxJava applied [JavaDay Kyiv 2016]Igor Lozynskyi
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 

Similaire à 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
 

Dernier

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 

Dernier (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 

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

Notes de l'éditeur

  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