SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
Promise, it'sasync!
SLUG Lightning 2015-09-24
@nevyn, @lookback
SPAsync
Nested scopes
!.fetchFromNetwork(input) { intermediate in
!.parseResponse(intermediate) { again in
dispatch_async(dispatch_get_main_queue()) {
updateUI(output)
}
}
}
Error handling
!.fetchFromNetwork(input, callback: { intermediate in
!.parseResponse(intermediate, callback: { again in
dispatch_async(dispatch_get_main_queue()) {
updateUI(output)
}
}, errback: { error in
displayError("when parsing response, ", error)
})
}, errback: { error in
// This error is VERY far away from fetchFromNetwork!
displayError("when fetching from network, ", error)
})
Cancellation
var cancelled = false
block var cancellable : Cancellable?
let operation = !.fetchFromNetwork(input, callback: { intermediate in
if(cancelled) return
cancellable = !.parseResponse(intermediate, callback: { again in
if(cancelled) return
...
})
})
func cancel() {
cancelled = true
operation.cancel()
cancellable?.stopOperation()
}
Dependencies
func !()...
Fourasync concepts
» A-value-in-the-future
» Error handler
» Cancellation
» Dependencies
GCD?NSOperation?
ReactiveCocoa?
C♯
Task/ "promise" / "future"
HelpmeApple,you're myonlyhope!
» A-value-in-the-future
» Error handler
» Cancellation
» Dependencies
... IN FOUNDATION
SPTask.swift 1/4
class TaskCompletionSource<T> {
public let task: Task<T>
func completeWithValue(value: T)
func failWithError(error: NSError!)
}
SPTask.swift 2/4
class Task<T> {
public func addCallback(
on queue: dispatch_queue_t,
callback: (T -> Void)
) -> Self
public func addErrorCallback(
on queue: dispatch_queue_t,
callback: (NSError! -> Void)
) -> Self
public func addFinallyCallback(
on queue: dispatch_queue_t,
callback: (Bool -> Void)
) -> Self
}
Callback example
// Two of these three are executed immediately after each other
network.fetch(resource).addCallback { json in
let modelObject = parse(json)
updateUI(modelObject)
}.addErrback { error in
displayDialog(error)
}.addFinally { cancelled in
if !cancelled {
viewController.dismiss()
}
}
SPTask.swift 3/4
class Task<T> {
public func then<T2>(on queue:dispatch_queue_t, worker: (T -> T2)) -> Task<T2>
public func then<T2>(chainer: (T -> Task<T2>)) -> Task<T2>
}
Chaining example
// A: inline background parsing on _worker_queue
func parse<T>(json) -> T
network.fetch(resource)
.then(on: _worker_queue) { json in
// First this function runs, running parse on _worker_queue...
return parse<MyModel>(json)
}.addCallback { modelObject in
// ... and when it's done, this function runs on main
updateUI(modelObject)
}.addErrorCallback { ... }
// B: background parsing on Parser's own thread with async method
class Parser {
func parse<T>(json) -> Task<T>
}
network.fetch(resource)
.then(_parser.parse) // parser is responsible for doing async work on its own
.addCallback(updateUI) // and then updateUI is called with the model object
.addErrorCallback(displayError)
SPTask.swift 4/4
class Task<T> {
public func cancel()
static func awaitAll(tasks: [Task]) -> Task<[Any]>
}
cancelandawaitAllexample
let imagesTask = Task.awaitAll(network.fetchImages(resource)).then { imageDatas in
return Task.awaitAll(imageDatas.map { data in
return parseImage(data)
})
}.addCallback { images in
showImages(image)
}
func viewDidDisappear()
{
// All downloading and parsing is cancelled
imagesTask.cancel()
}
Grand finale
Task.wrap()
class NSURLConnection {
func sendAsynchronousRequest(
request: NSURLRequest,
queue: NSOperationQueue,
completionHandler: (NSURLResponse?, NSError?) -> Void
)
}
extension NSURLConnection {
// : (NSURLRequest, queue) -> Task<NSURLResponse?>
let asyncTaskRequest = Task.wrap(NSURLConnection.sendAsynchronousRequest)
}
NSURLConnection.asyncTaskRequest(myRequest, mainQueue)
.then(_parser.parse)
.then(_db.store)
.then(_ui.update)
extension Task {
func wrap<P1, P2, R1> (
asyncFunction: (
p1: P1,
p2: P2,
callback: (
r1: R1,
err: NSError?
) -> Void
) -> Void
) -> (P1, P2) -> Task<R1>
}
extension Task {
func wrap<P1, P2, R1> (
asyncFunction: (
p1: P1,
p2: P2,
callback: (
r1: R1,
err: NSError?
) -> Void
) -> Void
) -> (P1, P2) -> Task<R1>
{
let source = TaskCompletionSource<R1>()
return { (p1: P1, p2: P2) -> Task<R1> in
asyncFunc(p1: p1, p2: p2, callback: { (r1: R1, error: NSError?) -> Void in
if let error = error {
source.failWithError(error)
} else {
source.completeWithValue(r1)
}
})
return source.task
}
}
}
FunctionalTask?
Monads? Applicatives? Huh?!
Blog: Methods ofConcurrency
 
http://bit.do/concurrency
http://overooped.com/post/41803252527/methods-of-
concurrency
Thankyou@nevyn
nevyn@lookback.io

Weitere ähnliche Inhalte

Was ist angesagt?

Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task QueueDuy Do
 
Debugging in Clojure: Finding Light in the Darkness using Emacs and Cursive
Debugging in Clojure: Finding Light in the Darkness using Emacs and CursiveDebugging in Clojure: Finding Light in the Darkness using Emacs and Cursive
Debugging in Clojure: Finding Light in the Darkness using Emacs and CursiveAhmad Ragab
 
Home Brewing R.U.M - Analyzing application performance with real user monitoring
Home Brewing R.U.M - Analyzing application performance with real user monitoringHome Brewing R.U.M - Analyzing application performance with real user monitoring
Home Brewing R.U.M - Analyzing application performance with real user monitoringAnkit Rastogi
 
Building Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmBuilding Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmWei Lin
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryKishor Kumar
 
How to write not breakable unit tests
How to write not breakable unit testsHow to write not breakable unit tests
How to write not breakable unit testsRafal Ksiazek
 
objection - runtime mobile exploration
objection - runtime mobile explorationobjection - runtime mobile exploration
objection - runtime mobile explorationSensePost
 
Puppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollectivePuppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollectivePuppet
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with CeleryNicolas Grasset
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Why Redux-Observable?
Why Redux-Observable?Why Redux-Observable?
Why Redux-Observable?Anna Su
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
Using OTP and gen_server Effectively
Using OTP and gen_server EffectivelyUsing OTP and gen_server Effectively
Using OTP and gen_server EffectivelyKen Pratt
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for freeBenotCaron
 
Advanced task management with Celery
Advanced task management with CeleryAdvanced task management with Celery
Advanced task management with CeleryMahendra M
 

Was ist angesagt? (20)

Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task Queue
 
Django Celery
Django Celery Django Celery
Django Celery
 
Ansible 2.0
Ansible 2.0Ansible 2.0
Ansible 2.0
 
Debugging in Clojure: Finding Light in the Darkness using Emacs and Cursive
Debugging in Clojure: Finding Light in the Darkness using Emacs and CursiveDebugging in Clojure: Finding Light in the Darkness using Emacs and Cursive
Debugging in Clojure: Finding Light in the Darkness using Emacs and Cursive
 
Celery
CeleryCelery
Celery
 
Home Brewing R.U.M - Analyzing application performance with real user monitoring
Home Brewing R.U.M - Analyzing application performance with real user monitoringHome Brewing R.U.M - Analyzing application performance with real user monitoring
Home Brewing R.U.M - Analyzing application performance with real user monitoring
 
Building Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmBuilding Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker Swarm
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with Celery
 
How to write not breakable unit tests
How to write not breakable unit testsHow to write not breakable unit tests
How to write not breakable unit tests
 
objection - runtime mobile exploration
objection - runtime mobile explorationobjection - runtime mobile exploration
objection - runtime mobile exploration
 
Puppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollectivePuppet Camp DC 2014: Managing Puppet with MCollective
Puppet Camp DC 2014: Managing Puppet with MCollective
 
Async java8
Async java8Async java8
Async java8
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with Celery
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Why Redux-Observable?
Why Redux-Observable?Why Redux-Observable?
Why Redux-Observable?
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
Using OTP and gen_server Effectively
Using OTP and gen_server EffectivelyUsing OTP and gen_server Effectively
Using OTP and gen_server Effectively
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for free
 
Advanced task management with Celery
Advanced task management with CeleryAdvanced task management with Celery
Advanced task management with Celery
 

Andere mochten auch

Wilk_PS Final Report
Wilk_PS Final ReportWilk_PS Final Report
Wilk_PS Final ReportAyla Wilk
 
Black Bear Hunting in Alaska BOW Presentation 2016
Black Bear Hunting in Alaska BOW Presentation 2016Black Bear Hunting in Alaska BOW Presentation 2016
Black Bear Hunting in Alaska BOW Presentation 2016Becky Schwanke
 
ICT op school, niet bij leren alleen
ICT op school, niet bij leren alleenICT op school, niet bij leren alleen
ICT op school, niet bij leren alleenPeter Keur
 
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) Design
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) DesignThe 44th Move — Deep Blue, Kasparov and the Future of (Visual) Design
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) DesignAndreas Markdalen
 
ExposiciónMatemáticas
ExposiciónMatemáticasExposiciónMatemáticas
ExposiciónMatemáticasalcatoto
 
Ejercicio 2 Programación Algoritmos.
 Ejercicio 2 Programación Algoritmos. Ejercicio 2 Programación Algoritmos.
Ejercicio 2 Programación Algoritmos.Matias Yampolsky
 
Pakistan strengths
Pakistan strengthsPakistan strengths
Pakistan strengthsAkhuwat
 
Education 1 : Brain development
Education 1 : Brain development Education 1 : Brain development
Education 1 : Brain development Farhana120316
 
Accommodation & presbyopia expected amplitude of accommodation
Accommodation  & presbyopia expected amplitude of accommodationAccommodation  & presbyopia expected amplitude of accommodation
Accommodation & presbyopia expected amplitude of accommodationkausar Ali
 
Examen mensual iv bi civica
Examen mensual iv bi civicaExamen mensual iv bi civica
Examen mensual iv bi civicaCARLOS ROSALES
 
Accomodation
AccomodationAccomodation
Accomodationstudent
 
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...Bikash Sapkota
 
Economy of Pakistan
Economy of PakistanEconomy of Pakistan
Economy of PakistanUltraspectra
 

Andere mochten auch (20)

Wilk_PS Final Report
Wilk_PS Final ReportWilk_PS Final Report
Wilk_PS Final Report
 
Zilli lia ppt
Zilli lia pptZilli lia ppt
Zilli lia ppt
 
Vuelta
VueltaVuelta
Vuelta
 
Black Bear Hunting in Alaska BOW Presentation 2016
Black Bear Hunting in Alaska BOW Presentation 2016Black Bear Hunting in Alaska BOW Presentation 2016
Black Bear Hunting in Alaska BOW Presentation 2016
 
ICT op school, niet bij leren alleen
ICT op school, niet bij leren alleenICT op school, niet bij leren alleen
ICT op school, niet bij leren alleen
 
Mundolinea10
Mundolinea10Mundolinea10
Mundolinea10
 
100 diapositivas
100 diapositivas100 diapositivas
100 diapositivas
 
8 vourch
8 vourch8 vourch
8 vourch
 
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) Design
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) DesignThe 44th Move — Deep Blue, Kasparov and the Future of (Visual) Design
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) Design
 
ExposiciónMatemáticas
ExposiciónMatemáticasExposiciónMatemáticas
ExposiciónMatemáticas
 
Ejercicio 2 Programación Algoritmos.
 Ejercicio 2 Programación Algoritmos. Ejercicio 2 Programación Algoritmos.
Ejercicio 2 Programación Algoritmos.
 
Pakistan strengths
Pakistan strengthsPakistan strengths
Pakistan strengths
 
Malfimakeup
MalfimakeupMalfimakeup
Malfimakeup
 
HDI
HDIHDI
HDI
 
Education 1 : Brain development
Education 1 : Brain development Education 1 : Brain development
Education 1 : Brain development
 
Accommodation & presbyopia expected amplitude of accommodation
Accommodation  & presbyopia expected amplitude of accommodationAccommodation  & presbyopia expected amplitude of accommodation
Accommodation & presbyopia expected amplitude of accommodation
 
Examen mensual iv bi civica
Examen mensual iv bi civicaExamen mensual iv bi civica
Examen mensual iv bi civica
 
Accomodation
AccomodationAccomodation
Accomodation
 
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...
 
Economy of Pakistan
Economy of PakistanEconomy of Pakistan
Economy of Pakistan
 

Ähnlich wie Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24

Service worker: discover the next web game changer
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changerSandro Paganotti
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
The Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous BeastsThe Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous BeastsFederico Galassi
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0Eyal Vardi
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programováníPeckaDesign.cz
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 

Ähnlich wie Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24 (20)

Service worker: discover the next web game changer
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changer
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
Why react matters
Why react mattersWhy react matters
Why react matters
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Fault tolerance made easy
Fault tolerance made easyFault tolerance made easy
Fault tolerance made easy
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
The Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous BeastsThe Strange World of Javascript and all its little Asynchronous Beasts
The Strange World of Javascript and all its little Asynchronous Beasts
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 

Kürzlich hochgeladen

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 

Kürzlich hochgeladen (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 

Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24

  • 1. Promise, it'sasync! SLUG Lightning 2015-09-24 @nevyn, @lookback
  • 3. Nested scopes !.fetchFromNetwork(input) { intermediate in !.parseResponse(intermediate) { again in dispatch_async(dispatch_get_main_queue()) { updateUI(output) } } }
  • 4. Error handling !.fetchFromNetwork(input, callback: { intermediate in !.parseResponse(intermediate, callback: { again in dispatch_async(dispatch_get_main_queue()) { updateUI(output) } }, errback: { error in displayError("when parsing response, ", error) }) }, errback: { error in // This error is VERY far away from fetchFromNetwork! displayError("when fetching from network, ", error) })
  • 5. Cancellation var cancelled = false block var cancellable : Cancellable? let operation = !.fetchFromNetwork(input, callback: { intermediate in if(cancelled) return cancellable = !.parseResponse(intermediate, callback: { again in if(cancelled) return ... }) }) func cancel() { cancelled = true operation.cancel() cancellable?.stopOperation() }
  • 7. Fourasync concepts » A-value-in-the-future » Error handler » Cancellation » Dependencies
  • 10. C♯
  • 11. Task/ "promise" / "future"
  • 12. HelpmeApple,you're myonlyhope! » A-value-in-the-future » Error handler » Cancellation » Dependencies ... IN FOUNDATION
  • 13. SPTask.swift 1/4 class TaskCompletionSource<T> { public let task: Task<T> func completeWithValue(value: T) func failWithError(error: NSError!) }
  • 14. SPTask.swift 2/4 class Task<T> { public func addCallback( on queue: dispatch_queue_t, callback: (T -> Void) ) -> Self public func addErrorCallback( on queue: dispatch_queue_t, callback: (NSError! -> Void) ) -> Self public func addFinallyCallback( on queue: dispatch_queue_t, callback: (Bool -> Void) ) -> Self }
  • 15. Callback example // Two of these three are executed immediately after each other network.fetch(resource).addCallback { json in let modelObject = parse(json) updateUI(modelObject) }.addErrback { error in displayDialog(error) }.addFinally { cancelled in if !cancelled { viewController.dismiss() } }
  • 16. SPTask.swift 3/4 class Task<T> { public func then<T2>(on queue:dispatch_queue_t, worker: (T -> T2)) -> Task<T2> public func then<T2>(chainer: (T -> Task<T2>)) -> Task<T2> }
  • 17. Chaining example // A: inline background parsing on _worker_queue func parse<T>(json) -> T network.fetch(resource) .then(on: _worker_queue) { json in // First this function runs, running parse on _worker_queue... return parse<MyModel>(json) }.addCallback { modelObject in // ... and when it's done, this function runs on main updateUI(modelObject) }.addErrorCallback { ... } // B: background parsing on Parser's own thread with async method class Parser { func parse<T>(json) -> Task<T> } network.fetch(resource) .then(_parser.parse) // parser is responsible for doing async work on its own .addCallback(updateUI) // and then updateUI is called with the model object .addErrorCallback(displayError)
  • 18. SPTask.swift 4/4 class Task<T> { public func cancel() static func awaitAll(tasks: [Task]) -> Task<[Any]> }
  • 19. cancelandawaitAllexample let imagesTask = Task.awaitAll(network.fetchImages(resource)).then { imageDatas in return Task.awaitAll(imageDatas.map { data in return parseImage(data) }) }.addCallback { images in showImages(image) } func viewDidDisappear() { // All downloading and parsing is cancelled imagesTask.cancel() }
  • 22. class NSURLConnection { func sendAsynchronousRequest( request: NSURLRequest, queue: NSOperationQueue, completionHandler: (NSURLResponse?, NSError?) -> Void ) } extension NSURLConnection { // : (NSURLRequest, queue) -> Task<NSURLResponse?> let asyncTaskRequest = Task.wrap(NSURLConnection.sendAsynchronousRequest) } NSURLConnection.asyncTaskRequest(myRequest, mainQueue) .then(_parser.parse) .then(_db.store) .then(_ui.update)
  • 23. extension Task { func wrap<P1, P2, R1> ( asyncFunction: ( p1: P1, p2: P2, callback: ( r1: R1, err: NSError? ) -> Void ) -> Void ) -> (P1, P2) -> Task<R1> }
  • 24. extension Task { func wrap<P1, P2, R1> ( asyncFunction: ( p1: P1, p2: P2, callback: ( r1: R1, err: NSError? ) -> Void ) -> Void ) -> (P1, P2) -> Task<R1> { let source = TaskCompletionSource<R1>() return { (p1: P1, p2: P2) -> Task<R1> in asyncFunc(p1: p1, p2: p2, callback: { (r1: R1, error: NSError?) -> Void in if let error = error { source.failWithError(error) } else { source.completeWithValue(r1) } }) return source.task } } }
  • 27.