SlideShare a Scribd company logo
1 of 37
Download to read offline
Add some FUN to your
Functional programming
with RXJS
Java…
Groovy…
and JavaScript
Senior UI Engineer at Netflix
We do a lot of RX stuff with…
About Me
bittersweetryan
About Me
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!
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
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
forEach
throttle
filter
map
distinctUntilChanged
reduce
Thinking Functionally!
!
Thinking Functionally
Replace loops with map, reduce, and filter.
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 submits =
Observable.fromEvent(input,'keypresses').
throttle().
map( function( e ){
return e.which
} );
!
var enters = submits.filter( function( key ) ){
return e.which === keys.enter;
}
!
var escapes = submits.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
Thank You.!
!
ranklam@netflix.com

@bittersweetryan!

More Related Content

What's hot

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
 

What's hot (20)

Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
 
The State of JavaScript
The State of JavaScriptThe State of JavaScript
The State of JavaScript
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt III
 
Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Map kit light
Map kit lightMap kit light
Map kit light
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test
 
RxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowRxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrow
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 

Viewers also liked

ReactiveX-SEA
ReactiveX-SEAReactiveX-SEA
ReactiveX-SEA
Yang Yang
 

Viewers also liked (20)

Rethink Async With RXJS
Rethink Async With RXJSRethink Async With RXJS
Rethink Async With RXJS
 
Reactive Extensions for JavaScript
Reactive Extensions for JavaScriptReactive Extensions for JavaScript
Reactive Extensions for JavaScript
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
Solit 2014, Реактивный Javascript. Победа над асинхронностью и вложенностью, ...
Solit 2014, Реактивный Javascript. Победа над асинхронностью и вложенностью, ...Solit 2014, Реактивный Javascript. Победа над асинхронностью и вложенностью, ...
Solit 2014, Реактивный Javascript. Победа над асинхронностью и вложенностью, ...
 
FRP with Ractive and RxJS
FRP with Ractive and RxJSFRP with Ractive and RxJS
FRP with Ractive and RxJS
 
ReactiveX-SEA
ReactiveX-SEAReactiveX-SEA
ReactiveX-SEA
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Programação reativa com RxJS e Angular
Programação reativa com RxJS e AngularProgramação reativa com RxJS e Angular
Programação reativa com RxJS e Angular
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Functional Reactive Angular 2
Functional Reactive Angular 2 Functional Reactive Angular 2
Functional Reactive Angular 2
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Reactive Programming and RxJS
Reactive Programming and RxJSReactive Programming and RxJS
Reactive Programming and RxJS
 
Reactive design: languages, and paradigms
Reactive design: languages, and paradigmsReactive design: languages, and paradigms
Reactive design: languages, and paradigms
 
RxJS - The Reactive Extensions for JavaScript
RxJS - The Reactive Extensions for JavaScriptRxJS - The Reactive Extensions for JavaScript
RxJS - The Reactive Extensions for JavaScript
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
Electron, databases, and RxDB
Electron, databases, and RxDBElectron, databases, and RxDB
Electron, databases, and RxDB
 

Similar to Add Some Fun to Your Functional Programming With RXJS

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 

Similar to Add Some Fun to Your Functional Programming With RXJS (20)

Rethink Async with RXJS
Rethink Async with RXJSRethink Async with RXJS
Rethink Async with RXJS
 
Rethink Async with RXJS
Rethink Async with RXJSRethink Async with RXJS
Rethink Async with RXJS
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
 
Design for succcess with react and storybook.js
Design for succcess with react and storybook.jsDesign for succcess with react and storybook.js
Design for succcess with react and storybook.js
 
PK chunking presentation from Tahoe Dreamin' 2016
PK chunking presentation from Tahoe Dreamin' 2016PK chunking presentation from Tahoe Dreamin' 2016
PK chunking presentation from Tahoe Dreamin' 2016
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
Forcelandia 2016 PK Chunking
Forcelandia 2016 PK ChunkingForcelandia 2016 PK Chunking
Forcelandia 2016 PK Chunking
 
ReactJS
ReactJSReactJS
ReactJS
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Spark with Elasticsearch
Spark with ElasticsearchSpark with Elasticsearch
Spark with Elasticsearch
 
React.js Basics - ConvergeSE 2015
React.js Basics - ConvergeSE 2015React.js Basics - ConvergeSE 2015
React.js Basics - ConvergeSE 2015
 
Cycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI frameworkCycle.js - A functional reactive UI framework
Cycle.js - A functional reactive UI framework
 
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Functional Programming in Go
Functional Programming in GoFunctional Programming in Go
Functional Programming in Go
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Add Some Fun to Your Functional Programming With RXJS