SlideShare a Scribd company logo
1 of 66
Download to read offline
Agenda
1. Reactive?
2. Mutability & Immutability
3. Functions & Higher-order functions
4. Why functions?
5. Functional for Reactive
Who is speaking?
• freelance software consultant based
in Vienna
• Vienna Scala User Group
• web, web, web
Who is speaking?
• freelance software consultant based in
Vienna
• Vienna Scala User Group
• web, web, web
• writing a book on reactive web-
applications
http://www.manning.com/
bernhardt
dotd051315au 50% discount
Did you say reactive?
Disambiguation
• Reactive Programming
• Functional Reactive Programming
• Reactive Application
• Responsive Web-Application
Disambiguation
• Reactive Programming async data flows
• Functional Reactive Programming async data flows + FP
• Reactive Application architectural pattern
• Responsive Web-Application Twitter Bootstrap
Why Reactive:
many cores
• End of the single-core multi-core era
• Many players in the space
• Tilera, Cavium
• Adapteva Parallela
• Xeon PHI
Why Reactive:
many cores
• Meizu MX4 Ubuntu Edition
• Octa-core MediaTek MT6595
chipset
• 2GB RAM / 20.7 MP rear camera,
2MP front-facing / 16GB built-in
flash storage
Why reactive:
distribution
(theory)
• scaling out to handle large loads
• scaling out / replication to handle
node failure
Why reactive:
distribution
(reality)
• networks, networks, networks
• they fail all the time
• Jepsen series1
1
http://aphyr.com
Reactive: how?
public class PaymentController {
public PaymentConfirmation makePayment(CreditCard card) { ... }
public PaymentHistory getPastPayments() { ... }
}
Reactive: how?
@Elastic(minNodes = 5, maxNodes = 15)
@Resilient(gracefullyHandleNetworkPartitions = true)
public class PaymentController {
@Responsive(latency = 500, timeUnit = TimeUnit.MILLISECONDS)
@MessageDriven(messageProvider = Provider.AKKA)
public PaymentConfirmation makePayment(CreditCard card) { ... }
@Responsive(latency = 800, timeUnit = TimeUnit.MILLISECONDS)
public PaymentHistory getPastPayments() { ... }
}
Why Reactive: summary
• distribution accross CPU cores
• distribution accross networked machines
• need tooling to work with this type of distribution
Mutable state
Why mutable ?
• memory expensive!
• can't afford to keep past state in it
• re-use, overwrite, optimize
Mutable issues - example 1
Mutable issues - example 1
$scope.reservation = {
id: 42,
start: moment({ hour: 13, minute: 15 }),
end: moment({ hour: 14, minute: 30 })
};
timeline.setOptions({
min: $scope.reservation.start.startOf('hour').toDate(),
max: $scope.reservation.start.add(3, 'hour').toDate()
});
Mutable issues - example 1
$scope.reservation = {
id: 42,
start: moment({ hour: 13, minute: 15 }),
end: moment({ hour: 14, minute: 30 })
};
timeline.setOptions({
min: $scope.reservation.start.clone().startOf('hour').toDate(),
max: $scope.reservation.start.clone().add(3, 'hour').toDate()
});
Mutable issues - example 2
car.setPosition(0);
car.setPosition(10);
Mutable issues - example 2
The problem with
locks / latches
• solution workaround for a broken
conceptual model
• huge coordination overhead! Even
more so when distributed
• hard to reason about
• performance hit
Mutability: summary
• increased difficulty for the programmer (moving parts)
• makes life hard when working concurrently
Immutable
state
Immutable state -
why now?
• main memory is cheap!
• disk memory is cheap!
We can afford copies of past state
around in order to reduce
coordination efforts
Immutable state -
how?
case class Car(brand: String, position: Int)
val car = Car(brand = "DeLorean", position = 0)
val movedCar = car.copy(position = 10)
val movedCarLaterOn = car.copy(position = 30)
Working with different
version
"Snapshots" of reality
Immutable state -
how?
• clever immutable data structures,
e.g. Bitmapped Vector Trie 2
• do not copy data around - point to
unchanged data instead
• constant time for all operations
2
http://lampwww.epfl.ch/papers/idealhashtrees.pdf
Immutable all the
way down
• immutability changes everything 3
• programming languages
• databases: insert-only, event
stores
• SSD drives
3
http://www.cidrdb.org/cidr2015/Papers/CIDR15_Paper16.pdf
Immutability: summary
• we can afford to keep everything, with good performance
• reduces the headeache of coordination accross CPU cores
and networked nodes
• audit trail of changes for free
Functions
Functions, the Starwars Lego way
(three kinds of awesome united)
Pure function
Side-effecting function
Side-effecting function
Side-effecting function
The dark side clouds everything. Impossible to see the future is.
-- Master Yoda
Again a pure function
(this time with a laser gun)
Hmm...
Function composition
Function composition
def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ...
def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ...
Function composition
def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ...
def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ...
def build(parts: (Head, Body, Legs, Hair), lg: LaserGun):
ArmedHanSolo =
arm(assemble(parts), lg)
Higher-order
functions
Definition
A function that takes
another function as
parameter (or produces a
function as result).
Higher-order
functions
val users: List[User] = ...
val (minors, majors) =
users.partition(_.age < 18)
Higher-order
functions
val users: List[User] = ...
val isMinor =
(user: User) => user.age < 18
val (minors, majors) =
users.partition(isMinor)
Higher-order functions
def AuthenticatedAction(f: Request => User => Result) = Action { request =>
findUser(request).map { user =>
f(request)(user)
} getOrElse {
Unauthorized("Get out!")
}
}
def showSettings = AuthenticatedAction { request =>
user =>
userSettingsService.findSettings(user).map { settings =>
Ok(views.html.settings(user, settings))
} getOrElse {
NotFound("We lost all your settings. Sorry.")
}
}
Functions - Why ?
Functions
• portable and re-usable behaviour
• data changes, behaviour can be re-
used
• functions as data transformation
pipelines
Functions = data transformation
pipelines
val addresses = users.filter(_.age > 18)
.map(_.address)
.sortBy(_.city)
Build increasingly complex behaviour through a series
of transformations driven by composing functions
Functional
for reactive
Reactive
applications
• distributed in nature
• need to be resilient to failure, adapt
to changes
• asynchronous all the way down
Asynchronous
callback hell
var fetchPriceList = function() {
$.get('/items', function(items) {
var priceList = [];
items.forEach(function(item, itemIndex) {
$.get('/prices', { itemId: item.id }, function(price) {
priceList.push({ item: item, price: price });
if ( priceList.length == items.length ) {
return priceList;
}
}).fail(function() {
priceList.push({ item: item });
if ( priceList.length == items.length ) {
return priceList;
}
});
}
}).fail(function() {
alert("Could not retrieve items");
});
}
Asynchronous &
functional
val fetchItems = WS.get("/items").getJSON[List[Item]]()
val fetchPrices = WS.get("/prices").getJSON[List[Price]]()
val itemPrices: Future[List[(Item, Option[Price])]] = for {
items <- fetchItems
prices <- fetchPrices
} yield {
item -> items.flatMap { item =>
prices.find(_.itemId == item.id)
}
}
itemPrices.recover {
case ce: ConnectionException =>
log.error("Could not retrieve items")
List.empty
}
Immutable
Function
Composition
Thank you
http://www.manning.com/bernhardt
code dotd051315au 50% discount
@elmanu / manuel@bernhardt.io
Questions?

More Related Content

What's hot

The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupkrivachy
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka featuresGrzegorz Duda
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsKonrad Malawski
 
Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Clustermiciek
 
The internet of (lego) trains
The internet of (lego) trainsThe internet of (lego) trains
The internet of (lego) trainsGrzegorz Duda
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupRoy Russo
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConfJohan Andrén
 
State of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeKonrad Malawski
 
Async – react, don't wait
Async – react, don't waitAsync – react, don't wait
Async – react, don't waitJohan Andrén
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesKonrad Malawski
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Johan Andrén
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)Konrad Malawski
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 

What's hot (20)

The dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetup
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Actor Model Akka Framework
Actor Model Akka FrameworkActor Model Akka Framework
Actor Model Akka Framework
 
Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Cluster
 
The internet of (lego) trains
The internet of (lego) trainsThe internet of (lego) trains
The internet of (lego) trains
 
Introduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users Group
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConf
 
State of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to comeState of Akka 2017 - The best is yet to come
State of Akka 2017 - The best is yet to come
 
Async – react, don't wait
Async – react, don't waitAsync – react, don't wait
Async – react, don't wait
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutes
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Building reactive distributed systems with Akka
Building reactive distributed systems with Akka Building reactive distributed systems with Akka
Building reactive distributed systems with Akka
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 

Viewers also liked

Game-based learning
Game-based learningGame-based learning
Game-based learningeandreeva
 
EAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint PresentationEAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint PresentationJose Vazquez
 
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...Tanil Ozkan
 
Eagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-DesignEagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-DesignJuliane Tran Cong
 
Career Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary AgesCareer Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary AgesMichael Fork
 
Gaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen könnenGaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen könnenSebastian Deterding
 
Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE Premier Farnell
 
Best Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTIBest Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTIChristine Shine
 
The eagle power point
The eagle power pointThe eagle power point
The eagle power pointYonit Weil
 
Wolf presentation
Wolf presentationWolf presentation
Wolf presentationXalus
 
MBTI Type Presentation--Introduction
MBTI Type Presentation--IntroductionMBTI Type Presentation--Introduction
MBTI Type Presentation--IntroductionStaci A. Inskeep
 
New electronics slides
New electronics slidesNew electronics slides
New electronics slidesjogajosh
 
12 Changes To Make You Happier at Work
12 Changes To Make You Happier at Work12 Changes To Make You Happier at Work
12 Changes To Make You Happier at WorkWhen I Work
 
Meme Powerpoint
Meme PowerpointMeme Powerpoint
Meme PowerpointConnor
 
Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)yeokm1
 

Viewers also liked (20)

When Dev met Ops
When Dev met OpsWhen Dev met Ops
When Dev met Ops
 
Game-based learning
Game-based learningGame-based learning
Game-based learning
 
EAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint PresentationEAGLE CadSoft v6.5 Powerpoint Presentation
EAGLE CadSoft v6.5 Powerpoint Presentation
 
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
Potentials of Augmented Reality and Virtual Reality for Mechanical Engineerin...
 
Eagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-DesignEagle Handbuch V6 manual de - PCB-Design
Eagle Handbuch V6 manual de - PCB-Design
 
Mbti for everybody ii
Mbti for everybody   iiMbti for everybody   ii
Mbti for everybody ii
 
Power supply
Power supplyPower supply
Power supply
 
Coca cola
Coca colaCoca cola
Coca cola
 
Mbti
MbtiMbti
Mbti
 
Career Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary AgesCareer Day - Engineering for Elementary Ages
Career Day - Engineering for Elementary Ages
 
Gaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen könnenGaming it: Was User Experience Designer von Game Designern lernen können
Gaming it: Was User Experience Designer von Game Designern lernen können
 
Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE Build Your Own PCB with EAGLE - Getting Start with EAGLE
Build Your Own PCB with EAGLE - Getting Start with EAGLE
 
Best Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTIBest Careers for Your Personality Type MBTI
Best Careers for Your Personality Type MBTI
 
The eagle power point
The eagle power pointThe eagle power point
The eagle power point
 
Wolf presentation
Wolf presentationWolf presentation
Wolf presentation
 
MBTI Type Presentation--Introduction
MBTI Type Presentation--IntroductionMBTI Type Presentation--Introduction
MBTI Type Presentation--Introduction
 
New electronics slides
New electronics slidesNew electronics slides
New electronics slides
 
12 Changes To Make You Happier at Work
12 Changes To Make You Happier at Work12 Changes To Make You Happier at Work
12 Changes To Make You Happier at Work
 
Meme Powerpoint
Meme PowerpointMeme Powerpoint
Meme Powerpoint
 
Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)Introduction to PCB Design (Eagle)
Introduction to PCB Design (Eagle)
 

Similar to 3 things you must know to think reactive - Geecon Kraków 2015

Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMManuel Bernhardt
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTPMustafa TURAN
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaHermann Hueck
 
What's Coming Next in Sencha Frameworks
What's Coming Next in Sencha FrameworksWhat's Coming Next in Sencha Frameworks
What's Coming Next in Sencha FrameworksGrgur Grisogono
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
From polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratchFrom polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratchSergi González Pérez
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)Igalia
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaYardena Meymann
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Event Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingEvent Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingGlobalLogic Ukraine
 

Similar to 3 things you must know to think reactive - Geecon Kraków 2015 (20)

Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVMVoxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
Voxxed Days Vienna - The Why and How of Reactive Web-Applications on the JVM
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
What's Coming Next in Sencha Frameworks
What's Coming Next in Sencha FrameworksWhat's Coming Next in Sencha Frameworks
What's Coming Next in Sencha Frameworks
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
huhu
huhuhuhu
huhu
 
From polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratchFrom polling to real time: Scala, Akka, and Websockets from scratch
From polling to real time: Scala, Akka, and Websockets from scratch
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
function* - ES6, generators, and all that (JSRomandie meetup, February 2014)
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Event Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingEvent Sourcing and Functional Programming
Event Sourcing and Functional Programming
 

More from Manuel Bernhardt

Is there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems HamburgIs there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems HamburgManuel Bernhardt
 
Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018Manuel Bernhardt
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?Manuel Bernhardt
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?Manuel Bernhardt
 
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 20178 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017Manuel Bernhardt
 
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware ofScala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware ofManuel Bernhardt
 
8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware of8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware ofManuel Bernhardt
 
Beyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practiceBeyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practiceManuel Bernhardt
 
Beyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practiceBeyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practiceManuel Bernhardt
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and countingManuel Bernhardt
 
Project Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 monthsProject Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 monthsManuel Bernhardt
 
Tips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 projectTips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 projectManuel Bernhardt
 

More from Manuel Bernhardt (16)

Is there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems HamburgIs there anybody out there? Reactive Systems Hamburg
Is there anybody out there? Reactive Systems Hamburg
 
Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018Is there anybody out there? Scala Days Berlin 2018
Is there anybody out there? Scala Days Berlin 2018
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?
 
Is there anybody out there?
Is there anybody out there?Is there anybody out there?
Is there anybody out there?
 
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 20178 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
8 akka anti-patterns you'd better be aware of - Reactive Summit Austin 2017
 
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware ofScala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
Scala Days Copenhagen - 8 Akka anti-patterns you'd better be aware of
 
8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware of8 Akka anti-patterns you'd better be aware of
8 Akka anti-patterns you'd better be aware of
 
Beyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practiceBeyond the buzzword: a reactive web-appliction in practice
Beyond the buzzword: a reactive web-appliction in practice
 
Beyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practiceBeyond the Buzzword - a reactive application in practice
Beyond the Buzzword - a reactive application in practice
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and counting
 
Writing a technical book
Writing a technical bookWriting a technical book
Writing a technical book
 
Project Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 monthsProject Phoenix - From PHP to the Play Framework in 3 months
Project Phoenix - From PHP to the Play Framework in 3 months
 
Scala - Java2Days Sofia
Scala - Java2Days SofiaScala - Java2Days Sofia
Scala - Java2Days Sofia
 
Tips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 projectTips and tricks for setting up a Play 2 project
Tips and tricks for setting up a Play 2 project
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala pitfalls
Scala pitfallsScala pitfalls
Scala pitfalls
 

Recently uploaded

The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsDILIPKUMARMONDAL6
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...Amil Baba Dawood bangali
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 

Recently uploaded (20)

The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teams
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 

3 things you must know to think reactive - Geecon Kraków 2015

  • 1.
  • 2. Agenda 1. Reactive? 2. Mutability & Immutability 3. Functions & Higher-order functions 4. Why functions? 5. Functional for Reactive
  • 3. Who is speaking? • freelance software consultant based in Vienna • Vienna Scala User Group • web, web, web
  • 4. Who is speaking? • freelance software consultant based in Vienna • Vienna Scala User Group • web, web, web • writing a book on reactive web- applications http://www.manning.com/ bernhardt dotd051315au 50% discount
  • 5. Did you say reactive?
  • 6. Disambiguation • Reactive Programming • Functional Reactive Programming • Reactive Application • Responsive Web-Application
  • 7. Disambiguation • Reactive Programming async data flows • Functional Reactive Programming async data flows + FP • Reactive Application architectural pattern • Responsive Web-Application Twitter Bootstrap
  • 8.
  • 9. Why Reactive: many cores • End of the single-core multi-core era • Many players in the space • Tilera, Cavium • Adapteva Parallela • Xeon PHI
  • 10. Why Reactive: many cores • Meizu MX4 Ubuntu Edition • Octa-core MediaTek MT6595 chipset • 2GB RAM / 20.7 MP rear camera, 2MP front-facing / 16GB built-in flash storage
  • 11.
  • 12. Why reactive: distribution (theory) • scaling out to handle large loads • scaling out / replication to handle node failure
  • 13. Why reactive: distribution (reality) • networks, networks, networks • they fail all the time • Jepsen series1 1 http://aphyr.com
  • 14.
  • 15. Reactive: how? public class PaymentController { public PaymentConfirmation makePayment(CreditCard card) { ... } public PaymentHistory getPastPayments() { ... } }
  • 16. Reactive: how? @Elastic(minNodes = 5, maxNodes = 15) @Resilient(gracefullyHandleNetworkPartitions = true) public class PaymentController { @Responsive(latency = 500, timeUnit = TimeUnit.MILLISECONDS) @MessageDriven(messageProvider = Provider.AKKA) public PaymentConfirmation makePayment(CreditCard card) { ... } @Responsive(latency = 800, timeUnit = TimeUnit.MILLISECONDS) public PaymentHistory getPastPayments() { ... } }
  • 17. Why Reactive: summary • distribution accross CPU cores • distribution accross networked machines • need tooling to work with this type of distribution
  • 19.
  • 20. Why mutable ? • memory expensive! • can't afford to keep past state in it • re-use, overwrite, optimize
  • 21.
  • 22.
  • 23. Mutable issues - example 1
  • 24. Mutable issues - example 1 $scope.reservation = { id: 42, start: moment({ hour: 13, minute: 15 }), end: moment({ hour: 14, minute: 30 }) }; timeline.setOptions({ min: $scope.reservation.start.startOf('hour').toDate(), max: $scope.reservation.start.add(3, 'hour').toDate() });
  • 25. Mutable issues - example 1 $scope.reservation = { id: 42, start: moment({ hour: 13, minute: 15 }), end: moment({ hour: 14, minute: 30 }) }; timeline.setOptions({ min: $scope.reservation.start.clone().startOf('hour').toDate(), max: $scope.reservation.start.clone().add(3, 'hour').toDate() });
  • 26. Mutable issues - example 2 car.setPosition(0); car.setPosition(10);
  • 27. Mutable issues - example 2
  • 28. The problem with locks / latches • solution workaround for a broken conceptual model • huge coordination overhead! Even more so when distributed • hard to reason about • performance hit
  • 29. Mutability: summary • increased difficulty for the programmer (moving parts) • makes life hard when working concurrently
  • 31. Immutable state - why now? • main memory is cheap! • disk memory is cheap! We can afford copies of past state around in order to reduce coordination efforts
  • 32. Immutable state - how? case class Car(brand: String, position: Int) val car = Car(brand = "DeLorean", position = 0) val movedCar = car.copy(position = 10) val movedCarLaterOn = car.copy(position = 30) Working with different version "Snapshots" of reality
  • 33. Immutable state - how? • clever immutable data structures, e.g. Bitmapped Vector Trie 2 • do not copy data around - point to unchanged data instead • constant time for all operations 2 http://lampwww.epfl.ch/papers/idealhashtrees.pdf
  • 34. Immutable all the way down • immutability changes everything 3 • programming languages • databases: insert-only, event stores • SSD drives 3 http://www.cidrdb.org/cidr2015/Papers/CIDR15_Paper16.pdf
  • 35. Immutability: summary • we can afford to keep everything, with good performance • reduces the headeache of coordination accross CPU cores and networked nodes • audit trail of changes for free
  • 37. Functions, the Starwars Lego way (three kinds of awesome united)
  • 41. Side-effecting function The dark side clouds everything. Impossible to see the future is. -- Master Yoda
  • 42. Again a pure function (this time with a laser gun)
  • 45. Function composition def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ... def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ...
  • 46. Function composition def assemble(parts: (Head, Body, Legs, Hair)): HanSolo = ... def arm(h: HanSolo, lg: LaserGun): ArmedHanSolo = ... def build(parts: (Head, Body, Legs, Hair), lg: LaserGun): ArmedHanSolo = arm(assemble(parts), lg)
  • 48. Definition A function that takes another function as parameter (or produces a function as result).
  • 49. Higher-order functions val users: List[User] = ... val (minors, majors) = users.partition(_.age < 18)
  • 50. Higher-order functions val users: List[User] = ... val isMinor = (user: User) => user.age < 18 val (minors, majors) = users.partition(isMinor)
  • 51. Higher-order functions def AuthenticatedAction(f: Request => User => Result) = Action { request => findUser(request).map { user => f(request)(user) } getOrElse { Unauthorized("Get out!") } } def showSettings = AuthenticatedAction { request => user => userSettingsService.findSettings(user).map { settings => Ok(views.html.settings(user, settings)) } getOrElse { NotFound("We lost all your settings. Sorry.") } }
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58. Functions • portable and re-usable behaviour • data changes, behaviour can be re- used • functions as data transformation pipelines
  • 59. Functions = data transformation pipelines val addresses = users.filter(_.age > 18) .map(_.address) .sortBy(_.city) Build increasingly complex behaviour through a series of transformations driven by composing functions
  • 60.
  • 62. Reactive applications • distributed in nature • need to be resilient to failure, adapt to changes • asynchronous all the way down
  • 63. Asynchronous callback hell var fetchPriceList = function() { $.get('/items', function(items) { var priceList = []; items.forEach(function(item, itemIndex) { $.get('/prices', { itemId: item.id }, function(price) { priceList.push({ item: item, price: price }); if ( priceList.length == items.length ) { return priceList; } }).fail(function() { priceList.push({ item: item }); if ( priceList.length == items.length ) { return priceList; } }); } }).fail(function() { alert("Could not retrieve items"); }); }
  • 64. Asynchronous & functional val fetchItems = WS.get("/items").getJSON[List[Item]]() val fetchPrices = WS.get("/prices").getJSON[List[Price]]() val itemPrices: Future[List[(Item, Option[Price])]] = for { items <- fetchItems prices <- fetchPrices } yield { item -> items.flatMap { item => prices.find(_.itemId == item.id) } } itemPrices.recover { case ce: ConnectionException => log.error("Could not retrieve items") List.empty }
  • 66. Thank you http://www.manning.com/bernhardt code dotd051315au 50% discount @elmanu / manuel@bernhardt.io Questions?