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

More Related Content

What's hot

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
 

What's hot (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
 

Viewers also liked

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
 

Viewers also liked (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
 

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

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

Recently uploaded

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
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 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
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
 

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.