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
PDF
Let it Flow - Introduction to Functional Reactive Programming
PPTX
jQuery
PPTX
Functional Reactive Programming with RxJS
PDF
Asynchronous Programming at Netflix
PPTX
Rxjs swetugg
PDF
Functional Reactive Programming in JavaScript
PPTX
From zero to hero with the reactive extensions for JavaScript
PDF
jQuery secrets
PPTX
jQuery
PPTX
Rxjs marble-testing
PPTX
Angular2 rxjs
PDF
jQuery's Secrets
PPTX
From zero to hero with the reactive extensions for java script
PDF
State of jQuery and Drupal
PPTX
Client Best Practices
PDF
RxJS 5 in Depth
PDF
Building a JavaScript Library
PDF
Under the hood of RxJS (Dimitris Livas) - GreeceJS #27
PDF
Rxjs kyivjs 2015
Add Some Fun to Your Functional Programming With RXJS
Let it Flow - Introduction to Functional Reactive Programming
jQuery
Functional Reactive Programming with RxJS
Asynchronous Programming at Netflix
Rxjs swetugg
Functional Reactive Programming in JavaScript
From zero to hero with the reactive extensions for JavaScript
jQuery secrets
jQuery
Rxjs marble-testing
Angular2 rxjs
jQuery's Secrets
From zero to hero with the reactive extensions for java script
State of jQuery and Drupal
Client Best Practices
RxJS 5 in Depth
Building a JavaScript Library
Under the hood of RxJS (Dimitris Livas) - GreeceJS #27
Rxjs kyivjs 2015
Ad

More from ColdFusionConference (20)

PDF
Api manager preconference
PDF
PDF
Building better SQL Server Databases
PDF
API Economy, Realizing the Business Value of APIs
PDF
Don't just pdf, Smart PDF
PDF
Crafting ColdFusion Applications like an Architect
PDF
Security And Access Control For APIS using CF API Manager
PDF
Monetizing Business Models: ColdFusion and APIS
PDF
Become a Security Rockstar with ColdFusion 2016
PDF
ColdFusion in Transit action
PDF
Developer Insights for Application Upgrade to ColdFusion 2016
PDF
Where is cold fusion headed
PDF
ColdFusion Keynote: Building the Agile Web Since 1995
PDF
Instant ColdFusion with Vagrant
PPT
Restful services with ColdFusion
PDF
Super Fast Application development with Mura CMS
PDF
Build your own secure and real-time dashboard for mobile and web
PDF
Why Everyone else writes bad code
PDF
Securing applications
PDF
Testing automaton
Api manager preconference
Building better SQL Server Databases
API Economy, Realizing the Business Value of APIs
Don't just pdf, Smart PDF
Crafting ColdFusion Applications like an Architect
Security And Access Control For APIS using CF API Manager
Monetizing Business Models: ColdFusion and APIS
Become a Security Rockstar with ColdFusion 2016
ColdFusion in Transit action
Developer Insights for Application Upgrade to ColdFusion 2016
Where is cold fusion headed
ColdFusion Keynote: Building the Agile Web Since 1995
Instant ColdFusion with Vagrant
Restful services with ColdFusion
Super Fast Application development with Mura CMS
Build your own secure and real-time dashboard for mobile and web
Why Everyone else writes bad code
Securing applications
Testing automaton
Ad

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation theory and applications.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
“AI and Expert System Decision Support & Business Intelligence Systems”
Digital-Transformation-Roadmap-for-Companies.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Advanced methodologies resolving dimensionality complications for autism neur...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Big Data Technologies - Introduction.pptx
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
Review of recent advances in non-invasive hemoglobin estimation
Understanding_Digital_Forensics_Presentation.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Spectral efficient network and resource selection model in 5G networks
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...

Rethink Async with RXJS