SlideShare una empresa de Scribd logo
1 de 79
Async JavaScript at Netflix
Jafar Husain
@jhusain
InfoQ.com: News & Community Site
• 750,000 unique visitors/month
• Published in 4 languages (English, Chinese, Japanese and Brazilian
Portuguese)
• Post content from our QCon conferences
• News 15-20 / week
• Articles 3-4 / week
• Presentations (videos) 12-15 / week
• Interviews 2-3 / week
• Books 1 / month
Watch the video with slide
synchronization on InfoQ.com!
http://www.infoq.com/presentations
/async-programming-netflix
Purpose of QCon
- to empower software development by facilitating the spread of
knowledge and innovation
Strategy
- practitioner-driven conference designed for YOU: influencers of
change and innovation in your teams
- speakers and topics driving the evolution and innovation
- connecting and catalyzing the influencers and innovators
Highlights
- attended by more than 12,000 delegates since 2007
- held in 9 cities worldwide
Presented at QCon San Francisco
www.qconsf.com
Who is Jafar?
Cross-Team Technical Lead for Netflix UIs
Architect of Netflix UI Data Platform
Member of JavaScript standards committee
(TC39)
16 years in the industry, formerly worked at
Microsoft and GE
This is the story of how Netflix solved
BIGasync problems
by thinking differently about
Events.
2014
321
Async Programming was very
HARD
The Netflix App was plagued by
Race Conditions
Memory Leaks
Complex State Machines
Uncaught Async Errors
Playing a Movie Asynchronously
function play(movieId, cancelButton, callback) {
var movieTicket,
playError,
tryFinish = function() {
if (playError) {
callback(null, playError);
}
else if (movieTicket && player.initialized) {
callback(null, ticket);
}
};
cancelButton.addEventListener(“click”, function() { playError = “cancelled”; }
if (!player.initialized) {
player.init(function(error) {
playError = error;
tryFinish();
}
}
authorizeMovie(function(error, ticket) {
playError = error;
movieTicket = ticket;
tryFinish();
});
});
function play(movieId, cancelButton, callback) {
var movieTicket,
playError,
tryFinish = function() {
if (playError) {
callback(null, playError);
}
else if (movieTicket && player.initialized) {
callback(null, ticket);
}
};
cancelButton.addEventListener(“click”, function() { playError = “cancelled”; }
if (!player.initialized) {
player.init(function(error) {
playError = error;
tryFinish();
});
}
authorizeMovie(function(error, ticket) {
playError = error;
movieTicket = ticket;
tryFinish();
});
});
function play(movieId, cancelButton, callback) {
var movieTicket,
playError,
tryFinish = function() {
if (playError) {
callback(null, playError);
}
else if (movieTicket && player.initialized) {
callback(null, ticket);
}
};
cancelButton.addEventListener(“click”, function() { playError = “cancelled”; }
if (!player.initialized) {
player.init(function(error) {
playError = error;
tryFinish();
});
}
authorizeMovie(function(error, ticket) {
playError = error;
movieTicket = ticket;
tryFinish();
});
});
function play(movieId, cancelButton, callback) {
var movieTicket,
playError,
tryFinish = function() {
if (playError) {
callback(null, playError);
}
else if (movieTicket && player.initialized) {
callback(null, ticket);
}
};
cancelButton.addEventListener(“click”, function() { playError = “cancelled”; }
if (!player.initialized) {
player.init(function(error) {
playError = error;
tryFinish();
}
}
authorizeMovie(function(error, ticket) {
playError = error;
movieTicket = ticket;
tryFinish();
});
});
the majority of Netflix’s async code
is written with just a few flexible
functions.
Today
But first a brief
JavaScript 6 tutorial…
Functions
x + 1function(x) { return x + 1; }x =>
function(x, y) { return x + y; }(x, y) x + y=>
JS
6
5
Fin.
ForEach
> [1, 2, 3].forEach(x => console.log(x))
> 1
> 2
> 3
>
Map
Map
> [1, 2, 3].map(x => x + 1)
> [2, 3, 4]
>
Filter
Filter
> [1, 2, 3].filter(x => x > 1)
> [2, 3]
>
concatAll
concatAll
> [ [1], [2, 3], [], [4] ].concatAll()
> [1, 2, 3, 4]
>
Map/Filter/ConcatAll
> [1, 2, 3].map(x => x + 1)
> [2, 3, 4]
> [1, 2, 3].filter(x => x > 1)
> [2, 3]
> [ [1], [2, 3], [], [4] ].concatAll()
> [1, 2, 3, 4]
>
Let’s use map, filter, and concatAll to
get a list of your favorite Netflix titles.
Top-rated Movies Collection
var getTopRatedFilms = user =>
user.videoLists.
map(videoList =>
videoList.videos.
filter(video => video.rating === 5.0)).
concatAll();
getTopRatedFilms(user).
forEach(film => console.log(film));
What if I told you…
…that you could create a drag event…
…with nearly the same code?
Top-rated Movies Collection
var getTopRatedFilms = user =>
user.videoLists.
map(videoList =>
videoList.videos.
filter(video => video.rating === 5.0)).
concatAll();
getTopRatedFilms(user).
forEach(film => console.log(film));
Mouse Drags Collection
var getElementDrags = elmt =>
elmt.mouseDowns.
map(mouseDown =>
document.mouseMoves.
filter takeUntil(document.mouseUps)).
concatAll();
getElementDrags(image).
forEach(pos => image.position = pos);
“What’s the difference between an Array…
[{x: 23, y: 44}, {x:27, y:55}, {x:27, y:55}]
… and an Event?
{x: 23, y: 44}...{x:27, y:55}.... {x:27, y:55}......
Events and Arrays are both
collections.
So why don’t we program
them the same way?
Iterator
Observer
?
Iterator
> var iterator = [1,2,3].iterator();
> { value: 1, done: false }
>
> console.log(iterator.next());
> console.log(iterator.next());
> { value: 2, done: false }
>> console.log(iterator.next());
> { value: 3, done: false }
>> console.log(iterator.next());
> { done: true }
>
Map, Filter, and ConcatAll can be
implemented using an Iterator.
Observer Pattern
> document.addEventListener(
“mousemove”,
function next(e) {
console.log(e);
});
> { clientX: 425, clientY: 543 }
> { clientX: 450, clientY: 558 }
> { clientX: 455, clientY: 562 }
> { clientX: 460, clientY: 743 }
> { clientX: 476, clientY: 760 }
> { clientX: 476, clientY: 760 }
> { clientX: 476, clientY: 760 }
Iterator Observerprogressively send information to consumer
The Iterator and Observer Pattern
are Symmetrical.
The authors of
“Design Patterns”
missedthis symmetry.
As a result, they gave
Iterator and Observer
different semantics.
So Many Push APIs
DOM Events
Websockets
Server-sent Events
Node Streams
Service Workers
jQuery Events
XMLHttpRequest
setInterval
Observable === Collection + Time
Introducing Observable
Observables can model…
Events
Animations
Async Server Requests
Reactive Extensions
Events as Streams
Open Source (Apache2)
Ported to many languages
C
.NET
JavaScript
Java (Netflix)
Objective-C
http://reactivex.io
Events to Observables
var mouseMoves =
Observable.
fromEvent(element, “mousemove”);
Adapt Push APIs to Observable
DOM Events
Websockets
Server-sent Events
Node Streams
Service Workers
jQuery Events
XMLHttpRequest
setInterval
Observable
Event Subscription
// “subscribe”
var handler = (e) => console.log(e);
document.addEventListener(“mousemoves”, handler);
// “unsubscribe”
document.removeEventListener(“mousemoves”, handler);
Observable.forEach
// “subscribe”
var subscription =
mouseMoves.forEach(console.log);
// “unsubscribe”
subscription.dispose();
Expanded Observable.forEach
// “subscribe”
var subscription =
mouseMoves.forEach(
// next data
event => console.log(event),
// error
error => console.error(error),
// completed
() => console.log(“done”));
// “unsubscribe”
subscription.dispose();
optional
Expanded Observable.forEach
// “subscribe”
var subscription =
mouseMoves.forEach({
onNext: event => console.log(event),
// error
onError: error => console.error(error),
// completed
onCompleted: () => console.log(“done”)
});
// “unsubscribe”
subscription.dispose();
Observer
Converting Events to Observables
Observable.fromEvent = function(dom, eventName) {
// returning Observable object
return {
forEach: function(observer) {
var handler = (e) => observer.onNext(e);
dom.addEventListener(eventName, handler);
// returning Subscription object
return {
dispose: function() {
dom.removeEventListener(eventName, handler);
}
};
}
};
}
Observable Literal
JS6
time
{1……2…………3}
ForEach
> {1……2…………3}.forEach(console.log)
> 1
>> 2
>> 3
>
time
> {1……2…………3}
Map
> {1……2…………3}.map(x => x + 1)
> 2
>> 3
>> 4
>
time
> 2
> 3
>
Filter
> {1……2…………3}.filter(x => x + 1)
>> 2
>
time
concatAll
[
[1]
[2, 3],
[],
[4]
].concatAll()
[1, 2, 3, 4]
concatAll
{
…{1}
………{2………………3},
……………{}
………………{4}
}.concatAll()
{…1…2………………3…4}
time
TakeUntil
{…1…2…………3}.takeUntil(
{……………4})
{…1…2…}
time
Source collection
Stop collection
Mouse Drags Collection
var getElementDrags = elmt =>
elmt.mouseDowns.
map(mouseDown =>
document.mouseMoves.
takeUntil(document.mouseUps)).
concatAll();
getElementDrags(image).
forEach(pos => image.position = pos);
mergeAll
{
…{1}
………{2………………3},
……………{}
………………{4}
}.mergeAll()
{…1…2……4………3}
time
switchLatest
{
…{1}
………{2………………3},
……………{}
………………{4}
}.switchLatest()
{…1…2……4}
time
subscription.dispose()
Don’t unsubscribe from Events.
Complete them when another
event fires.
Mouse Drags Collection
var getElementDrags = elmt =>
elmt.mouseDowns.
map(mouseDown =>
document.mouseMoves.
takeUntil(document.mouseUps)).
concatAll();
getElementDrags(image).
forEach(pos => image.position = pos);
Netflix Search
Netflix Search
var searchResultSets =
keyPresses.
throttle(250).
map(key =>
getJSON(“/searchResults?q=” + input.value).
retry(3).
takeUntil(keyPresses)).
concatAll();
searchResultSets.forEach(
resultSet => updateSearchResults(resultSet),
error => showMessage(“the server appears to be down.”));
Netflix Search
var searchResultSets =
keyPresses.
throttle(250).
map(key =>
getJSON(“/searchResults?q=” + input.value).
retry(3).
takeUntil(keyPresses)).
concatAll switchLatest();
searchResultSets.forEach(
resultSet => updateSearchResults(resultSet),
error => showMessage(“the server appears to be down.”));
Netflix Search
var searchResultSets =
keyPresses.
throttle(250).
map(key =>
getJSON(“/searchResults?q=” + input.value).
retry(3)).
switchLatest();
searchResultSets.forEach(
resultSet => updateSearchResults(resultSet),
error => showMessage(“the server appears to be down.”));
Netflix Player
Player Callback Hell
function play(movieId, cancelButton, callback) {
var movieTicket,
playError,
tryFinish = function() {
if (playError) {
callback(null, playError);
}
else if (movieTicket && player.initialized) {
callback(null, ticket);
}
};
cancelButton.addEventListener(“click”, function() { playError = “cancel”; });
if (!player.initialized) {
player.init(function(error) {
playError = error;
tryFinish();
}
}
authorizeMovie(movieId, function(error, ticket) {
playError = error;
movieTicket = ticket;
tryFinish();
});
});
Player with Observable
var authorizations =
player.
init().
map(() =>
playAttempts.
map(movieId =>
player.authorize(movieId).
catch(e => Observable.empty).
takeUntil(cancels)).
concatAll())).
concatAll();
authorizations.forEach(
license => player.play(license),
error => showDialog(“Sorry, can’t play right now.”));
Netflix: Observable Everywhere
App Startup
Player
Data Access
Animations
View/Model binding
Interactive Learning Exercises
http://jhusain.github.io/learnrx/
Observable in JavaScript 7?
async function* getStocks() {
let reader = new AsyncFileReader(“stocks.txt”);
try {
while(!reader.eof) {
let line = await reader.readLine();
await yield JSON.parse(line);
}
}
finally {
reader.close();
}
}
async function writeStockInfos() {
let writer = new AsyncFileWriter(“stocksAndPrices.txt”);
try {
for(let name on getStocks()) {
let price = await getStockPrice(name);
await writer.writeLine(JSON.stringify({name, price}));
}
}
finally {
writer.close();
}
}
Resources
 reactivetrader.azurewebsites.net
 https://github.com/Reactive-Extensions/RxJS
 RxJava
 http://jhusain.github.io/learnrx/
 @jhusain
Questions
Watch the video with slide synchronization
on InfoQ.com!
http://www.infoq.com/presentations/async-
programming-netflix

Más contenido relacionado

La actualidad más candente

Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design PatternsBobby Bouwmann
 
1.suryo_atmojo-materi react-native 1 (mengenal react-native)
1.suryo_atmojo-materi react-native 1 (mengenal react-native)1.suryo_atmojo-materi react-native 1 (mengenal react-native)
1.suryo_atmojo-materi react-native 1 (mengenal react-native)Suryo Atmojo
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
 
Introduce yourself to java 17
Introduce yourself to java 17Introduce yourself to java 17
Introduce yourself to java 17ankitbhandari32
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsLilia Sfaxi
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Design Principles for a High-Performance Smalltalk
Design Principles for a High-Performance SmalltalkDesign Principles for a High-Performance Smalltalk
Design Principles for a High-Performance SmalltalkESUG
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Scott Wlaschin
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 
002- JavaFX Tutorial - Getting Started
002- JavaFX Tutorial - Getting Started002- JavaFX Tutorial - Getting Started
002- JavaFX Tutorial - Getting StartedMohammad Hossein Rimaz
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data StorageMingHo Chang
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 

La actualidad más candente (20)

Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
1.suryo_atmojo-materi react-native 1 (mengenal react-native)
1.suryo_atmojo-materi react-native 1 (mengenal react-native)1.suryo_atmojo-materi react-native 1 (mengenal react-native)
1.suryo_atmojo-materi react-native 1 (mengenal react-native)
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Cours design pattern m youssfi partie 6 proxy
Cours design pattern m youssfi partie 6 proxyCours design pattern m youssfi partie 6 proxy
Cours design pattern m youssfi partie 6 proxy
 
Introduce yourself to java 17
Introduce yourself to java 17Introduce yourself to java 17
Introduce yourself to java 17
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Spring boot
Spring bootSpring boot
Spring boot
 
Design Principles for a High-Performance Smalltalk
Design Principles for a High-Performance SmalltalkDesign Principles for a High-Performance Smalltalk
Design Principles for a High-Performance Smalltalk
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
002- JavaFX Tutorial - Getting Started
002- JavaFX Tutorial - Getting Started002- JavaFX Tutorial - Getting Started
002- JavaFX Tutorial - Getting Started
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesThreading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data Storage
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 

Similar a Asynchronous Programming at Netflix

Reactive Programming with Rx
 Reactive Programming with Rx Reactive Programming with Rx
Reactive Programming with RxC4Media
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service WorkerAnna Su
 
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W... 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...Robert Nyman
 
WebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.jsWebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.jsRobert Nyman
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015Fernando Daciuk
 
mobl presentation @ IHomer
mobl presentation @ IHomermobl presentation @ IHomer
mobl presentation @ IHomerzefhemel
 
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07Frédéric Harper
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopPeter Friese
 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileFirefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileRobert Nyman
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityDerek Lee Boire
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your appsJuan C Catalan
 
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28Frédéric Harper
 
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12Frédéric Harper
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widgetTudor Barbu
 
mobl - model-driven engineering lecture
mobl - model-driven engineering lecturemobl - model-driven engineering lecture
mobl - model-driven engineering lecturezefhemel
 

Similar a Asynchronous Programming at Netflix (20)

Reactive Programming with Rx
 Reactive Programming with Rx Reactive Programming with Rx
Reactive Programming with Rx
 
mobl
moblmobl
mobl
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service Worker
 
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W... 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
 
WebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.jsWebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.js
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
mobl presentation @ IHomer
mobl presentation @ IHomermobl presentation @ IHomer
mobl presentation @ IHomer
 
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
HTML pour le web mobile, Firefox OS - Devfest Nantes - 2014-11-07
 
Firebase & SwiftUI Workshop
Firebase & SwiftUI WorkshopFirebase & SwiftUI Workshop
Firebase & SwiftUI Workshop
 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileFirefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobile
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your apps
 
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
Firefox OS, fixing the mobile web - FITC Toronto - 2014-04-28
 
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
Firefox OS, HTML5 to the next level - Python Montreal - 2014-05-12
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
mobl - model-driven engineering lecture
mobl - model-driven engineering lecturemobl - model-driven engineering lecture
mobl - model-driven engineering lecture
 

Más de C4Media

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoC4Media
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileC4Media
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020C4Media
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsC4Media
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No KeeperC4Media
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like OwnersC4Media
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaC4Media
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideC4Media
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDC4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine LearningC4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at SpeedC4Media
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsC4Media
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsC4Media
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleC4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeC4Media
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereC4Media
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing ForC4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data EngineeringC4Media
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 

Más de C4Media (20)

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live Video
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy Mobile
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 

Último

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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 TerraformAndrey Devyatkin
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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 DevelopmentsTrustArc
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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 DiscoveryTrustArc
 
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...apidays
 
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 WorkerThousandEyes
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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)wesley chun
 
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...Drew Madelung
 

Último (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
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...
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 

Asynchronous Programming at Netflix

  • 1. Async JavaScript at Netflix Jafar Husain @jhusain
  • 2. InfoQ.com: News & Community Site • 750,000 unique visitors/month • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • News 15-20 / week • Articles 3-4 / week • Presentations (videos) 12-15 / week • Interviews 2-3 / week • Books 1 / month Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations /async-programming-netflix
  • 3. Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide Presented at QCon San Francisco www.qconsf.com
  • 4. Who is Jafar? Cross-Team Technical Lead for Netflix UIs Architect of Netflix UI Data Platform Member of JavaScript standards committee (TC39) 16 years in the industry, formerly worked at Microsoft and GE
  • 5. This is the story of how Netflix solved BIGasync problems by thinking differently about Events.
  • 8. The Netflix App was plagued by Race Conditions Memory Leaks Complex State Machines Uncaught Async Errors
  • 9. Playing a Movie Asynchronously function play(movieId, cancelButton, callback) { var movieTicket, playError, tryFinish = function() { if (playError) { callback(null, playError); } else if (movieTicket && player.initialized) { callback(null, ticket); } }; cancelButton.addEventListener(“click”, function() { playError = “cancelled”; } if (!player.initialized) { player.init(function(error) { playError = error; tryFinish(); } } authorizeMovie(function(error, ticket) { playError = error; movieTicket = ticket; tryFinish(); }); }); function play(movieId, cancelButton, callback) { var movieTicket, playError, tryFinish = function() { if (playError) { callback(null, playError); } else if (movieTicket && player.initialized) { callback(null, ticket); } }; cancelButton.addEventListener(“click”, function() { playError = “cancelled”; } if (!player.initialized) { player.init(function(error) { playError = error; tryFinish(); }); } authorizeMovie(function(error, ticket) { playError = error; movieTicket = ticket; tryFinish(); }); }); function play(movieId, cancelButton, callback) { var movieTicket, playError, tryFinish = function() { if (playError) { callback(null, playError); } else if (movieTicket && player.initialized) { callback(null, ticket); } }; cancelButton.addEventListener(“click”, function() { playError = “cancelled”; } if (!player.initialized) { player.init(function(error) { playError = error; tryFinish(); }); } authorizeMovie(function(error, ticket) { playError = error; movieTicket = ticket; tryFinish(); }); }); function play(movieId, cancelButton, callback) { var movieTicket, playError, tryFinish = function() { if (playError) { callback(null, playError); } else if (movieTicket && player.initialized) { callback(null, ticket); } }; cancelButton.addEventListener(“click”, function() { playError = “cancelled”; } if (!player.initialized) { player.init(function(error) { playError = error; tryFinish(); } } authorizeMovie(function(error, ticket) { playError = error; movieTicket = ticket; tryFinish(); }); });
  • 10. the majority of Netflix’s async code is written with just a few flexible functions. Today
  • 11. But first a brief JavaScript 6 tutorial…
  • 12. Functions x + 1function(x) { return x + 1; }x => function(x, y) { return x + y; }(x, y) x + y=> JS 6 5
  • 13. Fin.
  • 14. ForEach > [1, 2, 3].forEach(x => console.log(x)) > 1 > 2 > 3 >
  • 15. Map
  • 16. Map > [1, 2, 3].map(x => x + 1) > [2, 3, 4] >
  • 18. Filter > [1, 2, 3].filter(x => x > 1) > [2, 3] >
  • 20. concatAll > [ [1], [2, 3], [], [4] ].concatAll() > [1, 2, 3, 4] >
  • 21. Map/Filter/ConcatAll > [1, 2, 3].map(x => x + 1) > [2, 3, 4] > [1, 2, 3].filter(x => x > 1) > [2, 3] > [ [1], [2, 3], [], [4] ].concatAll() > [1, 2, 3, 4] >
  • 22.
  • 23. Let’s use map, filter, and concatAll to get a list of your favorite Netflix titles.
  • 24. Top-rated Movies Collection var getTopRatedFilms = user => user.videoLists. map(videoList => videoList.videos. filter(video => video.rating === 5.0)). concatAll(); getTopRatedFilms(user). forEach(film => console.log(film));
  • 25. What if I told you… …that you could create a drag event… …with nearly the same code?
  • 26. Top-rated Movies Collection var getTopRatedFilms = user => user.videoLists. map(videoList => videoList.videos. filter(video => video.rating === 5.0)). concatAll(); getTopRatedFilms(user). forEach(film => console.log(film));
  • 27. Mouse Drags Collection var getElementDrags = elmt => elmt.mouseDowns. map(mouseDown => document.mouseMoves. filter takeUntil(document.mouseUps)). concatAll(); getElementDrags(image). forEach(pos => image.position = pos);
  • 28. “What’s the difference between an Array… [{x: 23, y: 44}, {x:27, y:55}, {x:27, y:55}]
  • 29. … and an Event? {x: 23, y: 44}...{x:27, y:55}.... {x:27, y:55}......
  • 30. Events and Arrays are both collections.
  • 31. So why don’t we program them the same way?
  • 32.
  • 33.
  • 35. Iterator > var iterator = [1,2,3].iterator(); > { value: 1, done: false } > > console.log(iterator.next()); > console.log(iterator.next()); > { value: 2, done: false } >> console.log(iterator.next()); > { value: 3, done: false } >> console.log(iterator.next()); > { done: true } >
  • 36. Map, Filter, and ConcatAll can be implemented using an Iterator.
  • 37. Observer Pattern > document.addEventListener( “mousemove”, function next(e) { console.log(e); }); > { clientX: 425, clientY: 543 } > { clientX: 450, clientY: 558 } > { clientX: 455, clientY: 562 } > { clientX: 460, clientY: 743 } > { clientX: 476, clientY: 760 } > { clientX: 476, clientY: 760 } > { clientX: 476, clientY: 760 }
  • 38. Iterator Observerprogressively send information to consumer
  • 39. The Iterator and Observer Pattern are Symmetrical.
  • 40.
  • 41. The authors of “Design Patterns” missedthis symmetry.
  • 42. As a result, they gave Iterator and Observer different semantics.
  • 43. So Many Push APIs DOM Events Websockets Server-sent Events Node Streams Service Workers jQuery Events XMLHttpRequest setInterval
  • 44. Observable === Collection + Time Introducing Observable
  • 46. Reactive Extensions Events as Streams Open Source (Apache2) Ported to many languages C .NET JavaScript Java (Netflix) Objective-C
  • 48. Events to Observables var mouseMoves = Observable. fromEvent(element, “mousemove”);
  • 49. Adapt Push APIs to Observable DOM Events Websockets Server-sent Events Node Streams Service Workers jQuery Events XMLHttpRequest setInterval Observable
  • 50. Event Subscription // “subscribe” var handler = (e) => console.log(e); document.addEventListener(“mousemoves”, handler); // “unsubscribe” document.removeEventListener(“mousemoves”, handler);
  • 51. Observable.forEach // “subscribe” var subscription = mouseMoves.forEach(console.log); // “unsubscribe” subscription.dispose();
  • 52. Expanded Observable.forEach // “subscribe” var subscription = mouseMoves.forEach( // next data event => console.log(event), // error error => console.error(error), // completed () => console.log(“done”)); // “unsubscribe” subscription.dispose(); optional
  • 53. Expanded Observable.forEach // “subscribe” var subscription = mouseMoves.forEach({ onNext: event => console.log(event), // error onError: error => console.error(error), // completed onCompleted: () => console.log(“done”) }); // “unsubscribe” subscription.dispose(); Observer
  • 54. Converting Events to Observables Observable.fromEvent = function(dom, eventName) { // returning Observable object return { forEach: function(observer) { var handler = (e) => observer.onNext(e); dom.addEventListener(eventName, handler); // returning Subscription object return { dispose: function() { dom.removeEventListener(eventName, handler); } }; } }; }
  • 56. ForEach > {1……2…………3}.forEach(console.log) > 1 >> 2 >> 3 > time > {1……2…………3}
  • 57. Map > {1……2…………3}.map(x => x + 1) > 2 >> 3 >> 4 > time
  • 58. > 2 > 3 > Filter > {1……2…………3}.filter(x => x + 1) >> 2 > time
  • 62. Mouse Drags Collection var getElementDrags = elmt => elmt.mouseDowns. map(mouseDown => document.mouseMoves. takeUntil(document.mouseUps)). concatAll(); getElementDrags(image). forEach(pos => image.position = pos);
  • 65. Don’t unsubscribe from Events. Complete them when another event fires.
  • 66. Mouse Drags Collection var getElementDrags = elmt => elmt.mouseDowns. map(mouseDown => document.mouseMoves. takeUntil(document.mouseUps)). concatAll(); getElementDrags(image). forEach(pos => image.position = pos);
  • 68. Netflix Search var searchResultSets = keyPresses. throttle(250). map(key => getJSON(“/searchResults?q=” + input.value). retry(3). takeUntil(keyPresses)). concatAll(); searchResultSets.forEach( resultSet => updateSearchResults(resultSet), error => showMessage(“the server appears to be down.”));
  • 69. Netflix Search var searchResultSets = keyPresses. throttle(250). map(key => getJSON(“/searchResults?q=” + input.value). retry(3). takeUntil(keyPresses)). concatAll switchLatest(); searchResultSets.forEach( resultSet => updateSearchResults(resultSet), error => showMessage(“the server appears to be down.”));
  • 70. Netflix Search var searchResultSets = keyPresses. throttle(250). map(key => getJSON(“/searchResults?q=” + input.value). retry(3)). switchLatest(); searchResultSets.forEach( resultSet => updateSearchResults(resultSet), error => showMessage(“the server appears to be down.”));
  • 72. Player Callback Hell function play(movieId, cancelButton, callback) { var movieTicket, playError, tryFinish = function() { if (playError) { callback(null, playError); } else if (movieTicket && player.initialized) { callback(null, ticket); } }; cancelButton.addEventListener(“click”, function() { playError = “cancel”; }); if (!player.initialized) { player.init(function(error) { playError = error; tryFinish(); } } authorizeMovie(movieId, function(error, ticket) { playError = error; movieTicket = ticket; tryFinish(); }); });
  • 73. Player with Observable var authorizations = player. init(). map(() => playAttempts. map(movieId => player.authorize(movieId). catch(e => Observable.empty). takeUntil(cancels)). concatAll())). concatAll(); authorizations.forEach( license => player.play(license), error => showDialog(“Sorry, can’t play right now.”));
  • 74. Netflix: Observable Everywhere App Startup Player Data Access Animations View/Model binding
  • 76. Observable in JavaScript 7? async function* getStocks() { let reader = new AsyncFileReader(“stocks.txt”); try { while(!reader.eof) { let line = await reader.readLine(); await yield JSON.parse(line); } } finally { reader.close(); } } async function writeStockInfos() { let writer = new AsyncFileWriter(“stocksAndPrices.txt”); try { for(let name on getStocks()) { let price = await getStockPrice(name); await writer.writeLine(JSON.stringify({name, price})); } } finally { writer.close(); } }
  • 79. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations/async- programming-netflix