SlideShare a Scribd company logo
Rethink Async with
RXJS
Senior UI Engineer at
About Me
bittersweetryan
ranklam@netflix.com
Before We Begin
Before We Begin
Be KIND to those of us with OCD and…
Before We Begin
Change those Dropbox icons to B&W!
Reactive
Programming!
Reactive Programming
Java…
Groovy…
and JavaScript
At Netflix do a lot of RX…
.NET…
We Build This With RXJS
Reactive Programming
What if?
The iterator pattern and observer met at a bar, !
fell in love, got married, and had a baby?
Reactive Programming
Reactive Programming
What if?
This baby would allow you to use the same code to !
respond to events and asynchronous operations?
Meet Observable
Observables
What to events and async functions have in common?
Observables
As a mouse moves, doesn’t it just emit coordinates?
Tracking Mouse Movements
Observables
Tracking Mouse Movements
1s 2s
Mousedown
0s
Mouseup
{x : 200, y: 521} {x : 240, y: 552} {x : 210, y: 602} {x : 199, y: 579}
{x : 221, y: 530} {x : 218, y: 570} {x : 200, y: 599}
Observables
var mouseMoves =
Observable.fromEvent( mouseDown )
.takeUntil( mouseUp )
.map( function( mouseEvent ){
return {
x : mouseEvent.clientX,
y : mouseEvent.clientY
};
} ) ;
!
mouseMoves.subscribe( function( cords ){
//do stuff for each mouse move cord
});
Mouse Moves Observable
Observables
Observables Everywhere!
• Events!
• AJAX Requests!
• Node Functions!
• Arrays!
• Promises!
• And more….
Observables
Why not another Async approach?
• Replayable!
• Composable!
• Cancellable!
• Cache-able!
• Shareable!
• Can emit multiple value-able
Functional Review!
(With an RX twist)
Functional Review
Map
Reduce
Filter
Zip
var searchResultsSets =
keyups.
map( function( key ){
return Observable.getJSON('/search?' +
input.value)
});
Functional Review
Map - Transforms data
var searchResultsSets = keyups.
filter( function ( key ){
return input.value.length > 1;
}).
map( function( key ){
return Observable.getJSON('/search?' +
input.value)
);
Functional Review
Filter - Narrows Collections
var html =
searchResultsSets.
reduce(function( prev,curr ) {
return prev + '<li>' + curr.name + '</li>';
},'' );
Functional Review
Reduce - Turns a collection into a single value
Initial prev value.
Functional Review
Zip - Combines two collections
var movies = [ 'Super Troopers', 'Pulp Fiction',
'Fargo' ] ;
var boxArts =[ '/cdn/23212/120x80',
'/cdn/73212/120x80','/cdn/99212/120x80' ] ;
!
var withArt = Observable.
zip(movies, boxarts, function(movie, boxart){
return {title : movie, boxart : boxart};
});
!
//[{title : 'Super Troo…', boxart : '/cdn…'},
// {title : 'Pulp Fict…', boxart : '/cdn…' },
// {title : 'Fargo', boxart : 'cdn…' } ]
Functional Review
Observable Data Streams Are Like Crazy Straws
keyPresses Observable
subscribe
throttle
filter
map
distinctUntilChanged
reduce
Thinking Functionally
Thinking Functionally
Replace loops with map.
searchResults = Observable.
getJSON(‘/people?’ + input.value);
!
searchResults.
forEach( function( reps ){
var names = [];
for( var i = 1; i < resp; i++ ){
var name = data[i].fName + ' ' +
data[i].lName;
names.push( name );
}
});
Thinking Functionally
Replace loops with map and reduce.
searchResults = Observable.
getJSON(‘/people?’ + input.value).
map( function( data ){
return data.fName + data.lName;
} );
!
searchResults.forEach( function( resp ){
//resp will now be the names array
})
Thinking Functionally
Replace if’s with filters.
var keyPresses = O.fromEvent( el, 'keyup' )
!
keyPresses.forEach( function( e ){
if( e.which === keys.enter ){ //=> no!
//do something
}
});
Thinking Functionally
Replace if’s with filters.
var enterPresses = O.fromEvent( el, 'keyup' )
.filter( function( e ){
return e.which && e.which === keys.enter;
});
!
enterPresses.forEach( function( e ){
//do something
});
Thinking Functionally
Don’t put too much in a single stream.
var submits = O.fromEvent(input,'keypresses').
throttle().
map( function( e ){
return e.which
} ).
filter( function( key ){
return key === keys.enter || keys.escape;
}).
map().
reduce().
...
Smaller streams are OK.
Thinking Functionally
var keys =
Observable.fromEvent(input,'keypresses').
throttle().
map( function( e ){
return e.which
} );
!
var enters = keys.filter( function( key ) ){
return e.which === keys.enter;
}
!
var escapes = keys.filter( function( key ) ){
Don’t put too much in a single stream.
Smaller streams are OK.
Flattening Patterns!
managing concurrency!
Observables = Events Over Time
Key presses over time…
.5s 1s 1.5s 2s 2.5s 3s
B R E A K IJ <- N G B A D
Observables = Events Over Time
1s 2s 3s 4s 5s 6s
BR
BRE
BREAK
BREAKJ
BREAKING
BREAKING BA
BREAKING BAD
Ajax requests over time…
The Three Musketeers
Goofy as merge
Donald as concat
Mickey as switchLatest
Starring
Flattening Patterns
merge - combines items in a collection as each item arrives
concat - combines collections in the order they arrived
switchLatest - switches to the latest collection that !
arrives
Merge
1s 2s
http://jsbin.com/wehusi/13/edit
data
data
data
data
Concat
1s 2s
http://jsbin.com/fejod/4/edit
!
!
data
data
data
data
SwitchLatest
!
1s 2s
data
data
data
data
Building Animated
AutoComplete!
Putting Everything Together
Animated Autocomplete
SearchBBrBreBreaBreak
Observables = Events Over Time
Simple Widget, High Complexity
• Respond to key presses
• Send off Ajax requests
• Animate out when search results become invalid
• Animate in when new search results come in
• Don’t show old results
• Make sure one animation is finished before starting 

another
var keyups =
Observable.
fromEvent( searchInput, 'keypress');
Animated Autocomplete
var searchResultsSets =
keyups.
filter( function ( e ){
return input.value.length > 1;
}).
map( function( e ){
return Observable.
getJSON('/search?' + input.value);
}).
switchLatest();
Animated Autocomplete
var animateOuts =
keyups.
map(function( resultSet ){
return animateOut(resultsDiv);
});
!
var animateIns =
searchResultsSets.
map( function( resultSet ){
return Observable.
of(resultsSet).
concat(animateIn(resultsDiv));
});
Animated Autocomplete
var resultSets =
animateOuts.
merge(animateIns).
concatAll();
!
resultSets.

forEach( function( resultSet ){
if (resultSet.length === 0) {
$('.search-results').addClass('hidden');
}
else {
resultsDiv.innerHTML = toHTML(resultSet );
}
} );
Animated Autocomplete
var keyups =
Observable.
fromEvent( searchInput, ‘keypress');
!var searchResultsSets =
keyups.
filter( function ( e ){
return input.value.length > 1;
}).
map( function( e ){
return Observable.
getJSON('/search?' + input.value);
}).
switchLatest();
var animateOuts =
keyups.
map(function( resultSet ){
return animateOut(resultsDiv);
});
!var animateIns =
searchResultsSets.
map( function( resultSet ){
return Observable.
of(resultsSet).
concat(animateIn(resultsDiv));
});
!var resultSets =
animateOuts.
merge(animateIns).
concatAll();
!resultSets.

forEach( function( resultSet ){
if (resultSet.length === 0) {
$('.search-results').addClass('hidden');
}
else {
resultsDiv.innerHTML = toHTML(resultSet );
}
} );
Animated Autocomplete
In Conclusion!
!
ranklam@netflix.com

@bittersweetryan!
In Conclusion
• Observables are a POWERFUL abstraction!
• Requires a bit of mental rewiring!
• The RX API is HUGE, take baby steps!
• Merging strategies are the key coordinating async!
• Compose streams of data from small streams
To Find Out More
• http://github.com/jhusain/learnrx!
• https://github.com/Reactive-Extensions/RxJS/tree/master/doc!
• Chat with me
Questions?!
Thank You.!
!
ranklam@netflix.com

@bittersweetryan!

More Related Content

PDF
Rethink Async With RXJS
PDF
Boom! Promises/A+ Was Born
PDF
Алексей Волков "Интерактивные декларативные графики на React+D3"
PDF
Box2D and libGDX
PDF
Asynchronous Programming with JavaScript
PDF
libGDX: Tiled Maps
PDF
Sequence diagrams
PDF
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Rethink Async With RXJS
Boom! Promises/A+ Was Born
Алексей Волков "Интерактивные декларативные графики на React+D3"
Box2D and libGDX
Asynchronous Programming with JavaScript
libGDX: Tiled Maps
Sequence diagrams
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera

Similar to Rethink Async with RXJS (20)

PDF
Add Some Fun to Your Functional Programming With RXJS
PPTX
Async Redux Actions With RxJS - React Rally 2016
PDF
PDF
React JS and why it's awesome
KEY
Mistakes I Made Building Netflix for the iPhone
KEY
jQuery Anti-Patterns for Performance & Compression
KEY
HTML5, CSS3, and other fancy buzzwords
KEY
jQuery Anti-Patterns for Performance
PDF
Functional Reactive Programming / Compositional Event Systems
PDF
Using Ember to Make a Bazillion Dollars
PDF
WT-4065, Superconductor: GPU Web Programming for Big Data Visualization, by ...
KEY
Your Library Sucks, and why you should use it.
PDF
ReactJS
PDF
JavaScript for Flex Devs
PPT
Lec11cgu_10.ppt
PDF
Building a game engine with jQuery
PPT
Lec11lecturlecturlecturlecturlecturlecturlecturlecturcgu_10.ppt
PDF
Forcelandia 2016 PK Chunking
PDF
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
PDF
The algebra of library design
Add Some Fun to Your Functional Programming With RXJS
Async Redux Actions With RxJS - React Rally 2016
React JS and why it's awesome
Mistakes I Made Building Netflix for the iPhone
jQuery Anti-Patterns for Performance & Compression
HTML5, CSS3, and other fancy buzzwords
jQuery Anti-Patterns for Performance
Functional Reactive Programming / Compositional Event Systems
Using Ember to Make a Bazillion Dollars
WT-4065, Superconductor: GPU Web Programming for Big Data Visualization, by ...
Your Library Sucks, and why you should use it.
ReactJS
JavaScript for Flex Devs
Lec11cgu_10.ppt
Building a game engine with jQuery
Lec11lecturlecturlecturlecturlecturlecturlecturlecturcgu_10.ppt
Forcelandia 2016 PK Chunking
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
The algebra of library design
Ad

More from devObjective (20)

PDF
Lets git together
PDF
Raspberry Pi a la CFML
PDF
Command box
PDF
Effective version control
PDF
Front end-modernization
PDF
Using type script to build better apps
PDF
Csp and http headers
PDF
Who owns Software Security
PDF
Naked and afraid Offline mobile
PDF
Web hackingtools 2015
PDF
Node without servers aws-lambda
PDF
I am-designer
PDF
Garbage First and You!
PDF
Fusion Reactor
PDF
Paying off emotional debt
PPTX
My SQL Skills Killed the Server
PDF
Authentication Control
PDF
Multiply like rabbits with rabbit mq
PPTX
Preso slidedeck
PDF
Intro to TDD & BDD
Lets git together
Raspberry Pi a la CFML
Command box
Effective version control
Front end-modernization
Using type script to build better apps
Csp and http headers
Who owns Software Security
Naked and afraid Offline mobile
Web hackingtools 2015
Node without servers aws-lambda
I am-designer
Garbage First and You!
Fusion Reactor
Paying off emotional debt
My SQL Skills Killed the Server
Authentication Control
Multiply like rabbits with rabbit mq
Preso slidedeck
Intro to TDD & BDD
Ad

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Modernizing your data center with Dell and AMD
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
Teaching material agriculture food technology
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
A Presentation on Artificial Intelligence
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Modernizing your data center with Dell and AMD
NewMind AI Weekly Chronicles - August'25 Week I
Spectral efficient network and resource selection model in 5G networks
Review of recent advances in non-invasive hemoglobin estimation
Advanced methodologies resolving dimensionality complications for autism neur...
Teaching material agriculture food technology
cuic standard and advanced reporting.pdf
NewMind AI Monthly Chronicles - July 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
MYSQL Presentation for SQL database connectivity
A Presentation on Artificial Intelligence
“AI and Expert System Decision Support & Business Intelligence Systems”
Bridging biosciences and deep learning for revolutionary discoveries: a compr...

Rethink Async with RXJS