SlideShare a Scribd company logo
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
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
Thankyou@nevyn
nevyn@lookback.io

More Related Content

PDF
Django Celery - A distributed task queue
ODP
Europython 2011 - Playing tasks with Django & Celery
PDF
Practical Celery
PDF
An Introduction to Celery
PPTX
Avoiding Callback Hell with Async.js
PDF
JavaOne 2015 - Having fun with Javassist
KEY
Loadrunner
PDF
clara-rules
Django Celery - A distributed task queue
Europython 2011 - Playing tasks with Django & Celery
Practical Celery
An Introduction to Celery
Avoiding Callback Hell with Async.js
JavaOne 2015 - Having fun with Javassist
Loadrunner
clara-rules

What's hot (20)

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

Viewers also liked (20)

DOCX
Wilk_PS Final Report
PPTX
Zilli lia ppt
PDF
Vuelta
PDF
Black Bear Hunting in Alaska BOW Presentation 2016
PPTX
ICT op school, niet bij leren alleen
TXT
Mundolinea10
PPTX
100 diapositivas
PPT
8 vourch
PDF
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) Design
PPTX
ExposiciónMatemáticas
DOCX
Ejercicio 2 Programación Algoritmos.
PPTX
Pakistan strengths
PPTX
Malfimakeup
PPTX
PPTX
Education 1 : Brain development
PPTX
Accommodation & presbyopia expected amplitude of accommodation
DOCX
Examen mensual iv bi civica
PPTX
Accomodation
PPTX
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...
PPTX
Economy of Pakistan
Wilk_PS Final Report
Zilli lia ppt
Vuelta
Black Bear Hunting in Alaska BOW Presentation 2016
ICT op school, niet bij leren alleen
Mundolinea10
100 diapositivas
8 vourch
The 44th Move — Deep Blue, Kasparov and the Future of (Visual) Design
ExposiciónMatemáticas
Ejercicio 2 Programación Algoritmos.
Pakistan strengths
Malfimakeup
Education 1 : Brain development
Accommodation & presbyopia expected amplitude of accommodation
Examen mensual iv bi civica
Accomodation
Accommodation/ Accommodation of Eye, Measurement of Accommodation of Eye (hea...
Economy of Pakistan
Ad

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

PDF
Your 🧠 on Swift Concurrency
PDF
async/await in Swift
PDF
Promise of an API
PDF
Async Await for Mobile Apps
PPT
Promise on iOs
PDF
Multithreading on iOS
PDF
Nikita Tuk: Handling background processes in iOS: problems & solutions
PDF
2013-05-15 threads. why and how
PDF
Implementing pseudo-keywords through Functional Programing
PDF
dotSwift - From Problem to Solution
PDF
Asynchronous swift
PPT
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
PDF
Asynchronous programming with Java & Spring
PDF
Let'swift "Concurrency in swift"
PDF
Async Debugging A Practical Guide to survive !
PDF
PyCon Canada 2019 - Introduction to Asynchronous Programming
PDF
Async await functions in ruby
PDF
MFF UK - Advanced iOS Topics
PPTX
Cancellation in coroutines
PDF
Coroutines
Your 🧠 on Swift Concurrency
async/await in Swift
Promise of an API
Async Await for Mobile Apps
Promise on iOs
Multithreading on iOS
Nikita Tuk: Handling background processes in iOS: problems & solutions
2013-05-15 threads. why and how
Implementing pseudo-keywords through Functional Programing
dotSwift - From Problem to Solution
Asynchronous swift
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
Asynchronous programming with Java & Spring
Let'swift "Concurrency in swift"
Async Debugging A Practical Guide to survive !
PyCon Canada 2019 - Introduction to Asynchronous Programming
Async await functions in ruby
MFF UK - Advanced iOS Topics
Cancellation in coroutines
Coroutines

Recently uploaded (20)

PDF
Nekopoi APK 2025 free lastest update
PDF
AI in Product Development-omnex systems
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
medical staffing services at VALiNTRY
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Digital Strategies for Manufacturing Companies
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Introduction to Artificial Intelligence
PDF
top salesforce developer skills in 2025.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
L1 - Introduction to python Backend.pptx
Nekopoi APK 2025 free lastest update
AI in Product Development-omnex systems
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
VVF-Customer-Presentation2025-Ver1.9.pptx
Design an Analysis of Algorithms I-SECS-1021-03
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
medical staffing services at VALiNTRY
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Digital Strategies for Manufacturing Companies
Design an Analysis of Algorithms II-SECS-1021-03
Navsoft: AI-Powered Business Solutions & Custom Software Development
Upgrade and Innovation Strategies for SAP ERP Customers
How to Migrate SBCGlobal Email to Yahoo Easily
Introduction to Artificial Intelligence
top salesforce developer skills in 2025.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
L1 - Introduction to python Backend.pptx

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 } } }