Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Introduction to FRP
Search
Stratos Pavlakis
July 21, 2015
Programming
250
3
Share
Introduction to FRP
An introduction to Functional Reactive Programming - presented at 9th GreeceJS meetup
Stratos Pavlakis
July 21, 2015
More Decks by Stratos Pavlakis
See All by Stratos Pavlakis
Intro to Remix
pavlakis
0
180
Gitting like a pro - Take 2.pdf
pavlakis
0
71
4th Virtual GreeceJS - Tech News
pavlakis
0
34
3rd Virtual GreeceJS - Tech News
pavlakis
0
47
PWAs: the Application Shell & the well of surprises
pavlakis
1
210
Error Handling in Javascript
pavlakis
1
220
Gitting like a Pro
pavlakis
1
290
Async Patterns & Paradigms in Javascript
pavlakis
4
330
Going Mobile
pavlakis
2
210
Other Decks in Programming
See All in Programming
運転動画を検索可能にする〜Cosmos-Embed1とDatabricks Vector Searchで〜/cosmos-embed1-databricks-vector-search
studio_graph
3
970
エラー処理の温故知新 / history of error handling technic
ryotanakaya
7
1.9k
【ディップ|26年新卒研修資料】OpenAPI/Swagger REST API研修
dip_tech
PRO
0
260
RailsTokyo 2026#4: AI様があれば、 Hotwireの弱点は消えるか?
naofumi
3
450
Import assertionsが消えた日~ECMAScriptの仕様はどう決まり、なぜ覆るのか~
bicstone
2
190
AWSはOSSをどのように 考えているのか?
akihisaikeda
0
130
Are We Really Coding 10× Faster with AI?
kohzas
0
200
Agent Skills を社内で育てる仕組み作り
jackchuka
1
2.2k
PHPでローカル環境用のSSL/TLS証明書を発行することはできるのか? #phpconkagawa
akase244
0
370
GoogleCloudとterraform完全に理解した
terisuke
1
200
なぜあなたのコードには「コシ」がないのか?〜AI時代に問う、最後まで美味しい設計と戦略〜 #phpconkagawa / phpconkagawa2026
shogogg
0
210
Skillは並べた。動かなかった。契約で繋いだ。— 65個のSkillから、自走する開発サイクルへ
junholee
0
660
Featured
See All Featured
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.2k
Documentation Writing (for coders)
carmenintech
77
5.3k
Fashionably flexible responsive web design (full day workshop)
malarkey
408
66k
Producing Creativity
orderedlist
PRO
348
40k
ラッコキーワード サービス紹介資料
rakko
1
3.3M
Believing is Seeing
oripsolob
1
130
Art, The Web, and Tiny UX
lynnandtonic
304
21k
Design of three-dimensional binary manipulators for pick-and-place task avoiding obstacles (IECON2024)
konakalab
0
430
Stewardship and Sustainability of Urban and Community Forests
pwiseman
0
200
DBのスキルで生き残る技術 - AI時代におけるテーブル設計の勘所
soudai
PRO
65
54k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
46
2.8k
Building a Scalable Design System with Sketch
lauravandoore
463
34k
Transcript
Functional Reactive Programming in Javascript
whoami Stratos Pavlakis Workable UI Tech Lead
[email protected]
th3hunt FRP
newbie!
what’s FRP?
let’s begin with
http://www.reactivemanifesto.org/ Responsive Message Driven Resilient Elastic
sweet dreams
so better start with
reactive paradigm var b = 1, c = 1; var
a = b + c; // a == 2 b = 10; • // a == ? • // imperative paradigm => a == 2 • // reactive paradigm => a == 11
front end development is it synchronous or asynchronous?
• User Input • AJAX • Web Sockets / SSE
• Web Workers • Animations • Cross origin frame communication • Updating the DOM we deal with
• User Input • AJAX • Web Sockets / SSE
• Web Workers • Animations • Cross origin frame communication • Updating the DOM most are async!
tools we use
callbacks var el = document.getElementById("my-button"); el.addEventListener("click", function () { console.log(‘my
button was clicked’); });
promises $http(endpoint1) .get({q: ‘frp’}) .then(function (data) { console.log(‘We got data
back from ajax %s’, data); }) .then(function (data) { return $http(endpoint2).get({id: data.id}); })
generators in ES7 async(function main() { var result1 = await
request( "http://endpoint.1" ); var data = JSON.parse( result1 ); var result2 = await request( "http://endpoint.2?id=" + data.id ); var resp = JSON.parse( result2 ); console.log( "Value: " + resp.value ); })
problems • callback hell • try / catch (except for
generators) • memory leaks • reduced composability
event driven programming we react to events
is reason about event streams what we’re really trying to
do
any number of values Array over any amount of time
f(time) / async an event stream would be
first class citizen of FRP observable
Observer Iterator Gang of Four - Design Patterns ES6 EventEmitter
array VS event
array === collection
events === collection
collections are iterable
observable === collection + time
observable API var subscription = myObservable.subscribe(function (val) { console.log(‘Next: %s’,
val); });
from the EventEmitter? so… how is that different
we know when it’s done var subscription = myObservable.subscribe( onNext,
onError, onCompleted ); like promises
we got set operators • map • flatMap • reduce
• merge • concat • zip
more operators • debounce • buffer • skipUntil • flatMapLatest
• combineLatest • switch • retry
observables can model • mouse clicks • key presses •
scrolling • animations • AJAX Polling, Web Sockets • timers • even… constants
operators http://rxmarbles.com/
filter
debounce
distinctUntilChanged
takeUntil
example please!
mousedown.flatMap((md) => { var startX = md.offsetX, startY = md.offsetY;
return mousemove.map((mm) => { return { left: mm.clientX - startX, top: mm.clientY - startY }; }).takeUntil(mouseup); }).subscribe((pos) => { dragTarget.style.top = pos.top + 'px'; dragTarget.style.left = pos.left + 'px'; }); drag & drop
Autocomplete yes I know, the classic example
requirements • filter queries • throttle requests • retry (overcome
network glitches) • avoid duplicate requests • match results to latest query • abort no longer valid requests
keyup => results var keyPress = $('#search').keyupAsObservable(); .keyPress.map((ev) => {
return ev.target.value; }) .filter((text) => { return text.length > 3; }) .debounce(500) .distinctUntilChanged() .flatMapLatest(search.retry(3).takeUntil(keyPress)) .map((d) => { return d.response[1]; }) .subscribe(showResults, showError); throttling no duplicate requests filtering match/abort response/results
gets even better
things we can do • cancel (can’t do with Promises)
• be lazy until a subscriber subscribes (cold) • setup datasource on first subscription • teardown datasource on disposal
not convinced yet?
observable future • TC39 proposal to add to ES7 ◦
https://github.com/zenparsing/es-observable • Angular 2 first class support • ReactJS first class support
http://victorsavkin.com/post/108837493941/better-support-for-functional-programming-in
Rx in production
still... • steep learning curve • old habits die hard
• tricky to work with classic MV* • poor/difficult documentation (is getting better)
libraries
• Rx.js (port of Reactive Extensions to JS) • Bacon.js
• Kefir (faster bacon :)
origins
Microsoft Research • A Brief Introduction to ActiveVRML - Conan
Elliott • Functional Reactive Animations - Conan Elliott & Paul Hudak
resources • Fran Tutorial - http://conal.net/fran/tutorial.htm • Simply Reactive -
http://conal.net/papers/simply-reactive/ • Reactive Extensions - https://github.com/Reactive-Extensions/RxJS • BaconJS - https://baconjs.github.io/ • Async JavaScript with Reactive Extensions (Jafar Husain) ◦ https://www.youtube.com/watch?v=XRYN2xt11Ek • RxJS at Modern Web UI (Ben Lesh) ◦ https://www.youtube.com/watch?v=yk_6eU3Hcwo • http://www.slideshare.net/stefanmayer13/functional-reactive-programming-with-rxjs • https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 • RxJSKoans - https://rxkoans.codeplex.com/ • RxMarbles - http://rxmarbles.com/ • Reactive programming and MVC (Aaron Stacy) ◦ http://aaronstacy.com/writings/reactive-programming-and-mvc/
None
Questions?