SlideShare una empresa de Scribd logo
1 de 37
Descargar para leer sin conexión
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!

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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

Destacado (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 a Add Some Fun to Your Functional Programming With RXJS

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

Similar a 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
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Add Some Fun to Your Functional Programming With RXJS