SlideShare a Scribd company logo
1 of 53
Download to read offline
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

What's hot

Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!
Nico Krijnen
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
Baidu, Inc.
 
Distributed Deep Learning with Apache Spark and TensorFlow with Jim Dowling
Distributed Deep Learning with Apache Spark and TensorFlow with Jim DowlingDistributed Deep Learning with Apache Spark and TensorFlow with Jim Dowling
Distributed Deep Learning with Apache Spark and TensorFlow with Jim Dowling
Databricks
 

What's hot (20)

Elk devops
Elk devopsElk devops
Elk devops
 
Event Driven Systems with Spring Boot, Spring Cloud Streams and Kafka
Event Driven Systems with Spring Boot, Spring Cloud Streams and KafkaEvent Driven Systems with Spring Boot, Spring Cloud Streams and Kafka
Event Driven Systems with Spring Boot, Spring Cloud Streams and Kafka
 
Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!Event Sourcing with Kotlin, who needs frameworks!
Event Sourcing with Kotlin, who needs frameworks!
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
Django Celery
Django Celery Django Celery
Django Celery
 
ksqlDB로 시작하는 스트림 프로세싱
ksqlDB로 시작하는 스트림 프로세싱ksqlDB로 시작하는 스트림 프로세싱
ksqlDB로 시작하는 스트림 프로세싱
 
Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
 Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S... Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with Celery
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
Deep Dive into Stateful Stream Processing in Structured Streaming with Tathag...
 
Apache Spark Core—Deep Dive—Proper Optimization
Apache Spark Core—Deep Dive—Proper OptimizationApache Spark Core—Deep Dive—Proper Optimization
Apache Spark Core—Deep Dive—Proper Optimization
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIO
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Spark streaming: Best Practices
Spark streaming: Best PracticesSpark streaming: Best Practices
Spark streaming: Best Practices
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Building a Versatile Analytics Pipeline on Top of Apache Spark with Mikhail C...
Building a Versatile Analytics Pipeline on Top of Apache Spark with Mikhail C...Building a Versatile Analytics Pipeline on Top of Apache Spark with Mikhail C...
Building a Versatile Analytics Pipeline on Top of Apache Spark with Mikhail C...
 
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
Apache Spark 2.0: A Deep Dive Into Structured Streaming - by Tathagata Das
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Distributed Deep Learning with Apache Spark and TensorFlow with Jim Dowling
Distributed Deep Learning with Apache Spark and TensorFlow with Jim DowlingDistributed Deep Learning with Apache Spark and TensorFlow with Jim Dowling
Distributed Deep Learning with Apache Spark and TensorFlow with Jim Dowling
 

Similar to Rethink Async With RXJS

jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
Paul Irish
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
Peter Higgins
 
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN][Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
崇之 清水
 

Similar to Rethink Async With RXJS (20)

Add Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJSAdd Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJS
 
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
 
Yavorsky
YavorskyYavorsky
Yavorsky
 
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
 
Mistakes I Made Building Netflix for the iPhone
Mistakes I Made Building Netflix for the iPhoneMistakes I Made Building Netflix for the iPhone
Mistakes I Made Building Netflix for the iPhone
 
jQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
 
HTML5, CSS3, and other fancy buzzwords
HTML5, CSS3, and other fancy buzzwordsHTML5, CSS3, and other fancy buzzwords
HTML5, CSS3, and other fancy buzzwords
 
jQuery Anti-Patterns for Performance
jQuery Anti-Patterns for PerformancejQuery Anti-Patterns for Performance
jQuery Anti-Patterns for Performance
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Using Ember to Make a Bazillion Dollars
Using Ember to Make a Bazillion DollarsUsing Ember to Make a Bazillion Dollars
Using Ember to Make a Bazillion Dollars
 
WT-4065, Superconductor: GPU Web Programming for Big Data Visualization, by ...
WT-4065, Superconductor: GPU Web Programming for Big Data Visualization, by  ...WT-4065, Superconductor: GPU Web Programming for Big Data Visualization, by  ...
WT-4065, Superconductor: GPU Web Programming for Big Data Visualization, by ...
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
ReactJS
ReactJSReactJS
ReactJS
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
Lec11cgu_10.ppt
Lec11cgu_10.pptLec11cgu_10.ppt
Lec11cgu_10.ppt
 
Building a game engine with jQuery
Building a game engine with jQueryBuilding a game engine with jQuery
Building a game engine with jQuery
 
Forcelandia 2016 PK Chunking
Forcelandia 2016 PK ChunkingForcelandia 2016 PK Chunking
Forcelandia 2016 PK Chunking
 
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN][Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
[Hatsune Miku] Shoot Frieza with Amazon Kinesis ! [EN]
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptx
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Buy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdfBuy Epson EcoTank L3210 Colour Printer Online.pdf
Buy Epson EcoTank L3210 Colour Printer Online.pdf
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 

Rethink Async With RXJS