SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Moar tools for asynchrony!
           @nevyn
• Background computation
                                               Building image,
                                              database search,
                                            (anything threaded)




• I/O          Network
                             Disk




           touch         app activation
• Events
                                              value changes (KVO)
             keyboard
                                  wifi connected
while(event = getNextEvent()) { // async event
 // possibly async IO, polling
   NSURL *pictureURL = [[Backend currentUser] profilePictureURL];

    // possibly async IO
      NSData *pictureData = [NSData dataWithContentsOfURL:pictureURL];

    // computation
      UIImage *profilePicture = [UIImage imageWithData:pictureData];
      if ([event touches:someRect]) {
         // IO
             UIImage *highlight = [UIImage imageNamed:@"profile-picture-highlight"];

      // computation
         profilePicture = [highlight imageCompositedOver:profilePicture];
     }
     [profilePicture drawInRect:someRect];
}
- (BOOL)application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

AudioSessionAddPropertyListener(
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
NULL
);

-[NSOperation setCompletionBlock:(void (^)(void))block];
// async event
- (void)touchesBegan:(NSArray*)touches withEvent:(UIEvent*)event {
    // async IO
   [[Backend currentUser] getProfilePictureURL:^ (NSURL*url) {
        // async IO
        [HTTPLibrary fetchURL:url onCompletion:^ (NSData *data) {
               // async processing
               dispatch_async(dispatch_get_global_queue(0,0), ^{
                     UIImage *profilePicture = [UIImage imageWithData:data];
                     … highlight …
                     dispatch_async(dispatch_get_main_queue(), ^{
                           imageView.image = profilePicture;
                     };
               }
        } error:^(NSError* err) {
               ...
        }];
   } onError:(NSError *err) {
        …
   }];
}
NSString *filename = ...;
NSData *maybeData = MALazyFuture(^{
    return [NSData dataWithContentsOfFile: filename];
});
[object doSomethingOrNotWithData: maybeData];


NSString *filename = ...;
NSData *futureData = MABackgroundFuture(^{
    return [NSData dataWithContentsOfFile: filename];
});
[object doSomethingLaterWithData: futureData];
NSString *filename = ...;
Task *futureData = TCBackgroundTask(^{
    return [NSData dataWithContentsOfFile: filename];
});

futureData.onDoneCallback = ^ (NSData *data) {
   [object doSomethingLaterWithData: futureData];
};

[futureData startOnQueue:dispatch_get_global_queue(0,0)];
Task *task = [[Backend currentUser] profilePictureURL];
NSURL *profilePictureURL = [task runSynchronously];
// I/O
Task *pictureTask = [UIImage imageFromURL:profilePictureURL];
// computation
Task *badgeTask = [UIImage imageNamedTask:@"profile-picture-highlight"];
// I/O
Task *colorTask = [[Backend currentUser] favoriteColor];

// Wait for all of the above to complete
[Task waitAll:pictureTask, badgeTask, colorTask, nil
    cancelOn:[CancellationToken cancelOnDismissed:self]];

// Use the fetched or computed values
UIImage *badgedImage = [[badgeTask value] composeOnTopOf: [pictureTask value]];
UIImage *coloredImage = [badgedImage tintedImage: [colorTask value]];
private async Task<byte[]> GetURLContentsAsync(string url)
{
  var content = new MemoryStream();
  HttpWebRequest webReq = WebRequest.Create(url);

 // GetResponseAsync returns a Task<WebResponse>.
 WebResponse response = await webReq.GetResponseAsync();   // “Pause” execution

 Stream responseStream = response.GetResponseStream();
 // CopyToAsync returns a Task
 await responseStream.CopyToAsync(content); // “Pause” execution

 return content.ToArray();
}
private async Task<byte[]> GetURLContentsAsync(string url)
{
  var content = new MemoryStream();
  HttpWebRequest webReq = WebRequest.Create(url);

 // GetResponseAsync returns a Task<WebResponse>.
 WebResponse response = await webReq.GetResponseAsync();

  Stream responseStream = response.GetResponseStream();
  // CopyToAsync returns a Task
  await responseStream.CopyToAsync(content);
                                private Task<byte[]> GetURLContentsAsync(string url)
                                {
  return content.ToArray();           var content = new MemoryStream();
}                                     HttpWebRequest webReq = WebRequest.Create(url);

                                      Task<WebResponse> responseTask = webReq.GetResponseAsync();
                                      Task task2 = responseTask.startAndCallback(^(WebResponse
                                response) {
                                            Stream responseStream = response.GetResponseStream();

                                            Task copyTask = responseStream.CopyToAsync(content);
                                            Task<byte[]> bytesTask = copyTask.startAndCallback(^ {
                                                  return content.ToArray();
                                            });
                                            return bytesTask;
                                      };
                                      return task2;
                                }
TCTask* GetURLContentsAsImageAsync(NSURL *url) {
 return [[[NSURLConnection requestURL:url] then:^ (id response) {
    return [response getDataAsync];

    } then:^ (NSData *data) {

          return TCBackgroundTask(^{
               [UIImage imageWithData:data];
          });

    }];
}
[[[TCRACSocket connectTo:@"localhost" port:1236]
selectMany:^id<RACSubscribable>(id x) {
    return [x lines];
}] subscribeNext:^(id x) {
    self.label.text = x;
} error:^(NSError *error) {
    NSLog(@"Failure: %@", error);
}];
• Objects <3
• Get un-stuck!

Weitere ähnliche Inhalte

Was ist angesagt?

Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part IAjit Nayak
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptSurvey Department
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185Mahmoud Samir Fayed
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt Passell
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIIAjit Nayak
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsNeo4j
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 
What they don't tell you about JavaScript
What they don't tell you about JavaScriptWhat they don't tell you about JavaScript
What they don't tell you about JavaScriptRaphael Cruzeiro
 
Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)Jonathan Katz
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsNeo4j
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020InfluxData
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010RonnBlack
 
[JAM 1.2] Design & Multitasking (Andrew Solovey)
[JAM 1.2] Design & Multitasking (Andrew Solovey)[JAM 1.2] Design & Multitasking (Andrew Solovey)
[JAM 1.2] Design & Multitasking (Andrew Solovey)Evgeny Kaziak
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 

Was ist angesagt? (20)

Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
 
Presto in Treasure Data
Presto in Treasure DataPresto in Treasure Data
Presto in Treasure Data
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
NS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt IIINS2: AWK and GNUplot - PArt III
NS2: AWK and GNUplot - PArt III
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
Theads services
Theads servicesTheads services
Theads services
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
What they don't tell you about JavaScript
What they don't tell you about JavaScriptWhat they don't tell you about JavaScript
What they don't tell you about JavaScript
 
Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)Accelerating Local Search with PostgreSQL (KNN-Search)
Accelerating Local Search with PostgreSQL (KNN-Search)
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
Gl qtp day 3 2
Gl qtp day 3   2Gl qtp day 3   2
Gl qtp day 3 2
 
Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020Time Series Meetup: Virtual Edition | July 2020
Time Series Meetup: Virtual Edition | July 2020
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
[JAM 1.2] Design & Multitasking (Andrew Solovey)
[JAM 1.2] Design & Multitasking (Andrew Solovey)[JAM 1.2] Design & Multitasking (Andrew Solovey)
[JAM 1.2] Design & Multitasking (Andrew Solovey)
 
I os 13
I os 13I os 13
I os 13
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 

Andere mochten auch

DH6004 Presentation
DH6004 PresentationDH6004 Presentation
DH6004 Presentationorlapeach
 
Huangshan Mountains By Alex
Huangshan Mountains  By AlexHuangshan Mountains  By Alex
Huangshan Mountains By Alexrommelc
 
θρεπτικά συστατικά
θρεπτικά συστατικάθρεπτικά συστατικά
θρεπτικά συστατικάChrysoula Katsougkri
 
Windridge Condominiums
Windridge CondominiumsWindridge Condominiums
Windridge CondominiumsMichael Fisher
 
Obiee beginner guide iv
Obiee beginner guide ivObiee beginner guide iv
Obiee beginner guide ivAmit Sharma
 
Established Practice In Photography
Established Practice In PhotographyEstablished Practice In Photography
Established Practice In Photographymjarry
 
2200m ah external battery charger pack case for samsung galaxy s2 i9100
2200m ah external battery charger pack case for samsung galaxy s2 i91002200m ah external battery charger pack case for samsung galaxy s2 i9100
2200m ah external battery charger pack case for samsung galaxy s2 i9100alicesun1999
 
γεωγραφια
γεωγραφιαγεωγραφια
γεωγραφιαxrysa123
 
"寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL
"寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL "寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL
"寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL cdoecrt
 
戒除甜食,享受健康
戒除甜食,享受健康戒除甜食,享受健康
戒除甜食,享受健康八正 文化
 
Tax avoidance debate timeline final
Tax avoidance debate timeline finalTax avoidance debate timeline final
Tax avoidance debate timeline finalDr Raj Thamotheram
 
แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559
แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559
แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559ประพันธ์ เวารัมย์
 

Andere mochten auch (18)

Apply for a Job Much?
Apply for a Job Much?Apply for a Job Much?
Apply for a Job Much?
 
DH6004 Presentation
DH6004 PresentationDH6004 Presentation
DH6004 Presentation
 
Huangshan Mountains By Alex
Huangshan Mountains  By AlexHuangshan Mountains  By Alex
Huangshan Mountains By Alex
 
θρεπτικά συστατικά
θρεπτικά συστατικάθρεπτικά συστατικά
θρεπτικά συστατικά
 
Windridge Condominiums
Windridge CondominiumsWindridge Condominiums
Windridge Condominiums
 
123
123123
123
 
Obiee beginner guide iv
Obiee beginner guide ivObiee beginner guide iv
Obiee beginner guide iv
 
Established Practice In Photography
Established Practice In PhotographyEstablished Practice In Photography
Established Practice In Photography
 
Capacity Planning
Capacity PlanningCapacity Planning
Capacity Planning
 
2200m ah external battery charger pack case for samsung galaxy s2 i9100
2200m ah external battery charger pack case for samsung galaxy s2 i91002200m ah external battery charger pack case for samsung galaxy s2 i9100
2200m ah external battery charger pack case for samsung galaxy s2 i9100
 
Module 2: Overview of Topics
Module 2: Overview of TopicsModule 2: Overview of Topics
Module 2: Overview of Topics
 
γεωγραφια
γεωγραφιαγεωγραφια
γεωγραφια
 
"寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL
"寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL "寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL
"寫代碼 - 一個監獄世界矩陣OUT SPIRITUAL
 
戒除甜食,享受健康
戒除甜食,享受健康戒除甜食,享受健康
戒除甜食,享受健康
 
Tax avoidance debate timeline final
Tax avoidance debate timeline finalTax avoidance debate timeline final
Tax avoidance debate timeline final
 
แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559
แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559
แจ้งผลการประชุม ก.จ. ก.ท. และ ก.อบต. ครั้งที่ 10/2559 เมื่อวันที่ 28 ตุลาคม 2559
 
Empirical Reasearch Project
Empirical Reasearch ProjectEmpirical Reasearch Project
Empirical Reasearch Project
 
spGiarelliMay2016
spGiarelliMay2016spGiarelliMay2016
spGiarelliMay2016
 

Ähnlich wie Moar tools for asynchrony!

Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCAWhymca
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applicationslmrei
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Satoshi Asano
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core DataMatthew Morey
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.Oleg Shanyuk
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots DeepAnshu Sharma
 
Dpilot - Source Code with Snapshots
Dpilot - Source Code with SnapshotsDpilot - Source Code with Snapshots
Dpilot - Source Code with SnapshotsKritika Phulli
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot Nidhi Chauhan
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataChris Mar
 
Parse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & TricksParse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & TricksHector Ramos
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKitTaras Kalapun
 
Effective iOS Network Programming Techniques
Effective iOS Network Programming TechniquesEffective iOS Network Programming Techniques
Effective iOS Network Programming TechniquesBen Scheirman
 
Edit the script in to disable code which adds demonstration entries to.pdf
Edit the script in to disable code which adds demonstration entries to.pdfEdit the script in to disable code which adds demonstration entries to.pdf
Edit the script in to disable code which adds demonstration entries to.pdfPeterM9sWhitej
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"ITGinGer
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)Katsumi Kishikawa
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone DevelopmentGiordano Scalzo
 

Ähnlich wie Moar tools for asynchrony! (20)

Beginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCABeginning icloud development - Cesare Rocchi - WhyMCA
Beginning icloud development - Cesare Rocchi - WhyMCA
 
Developing iOS REST Applications
Developing iOS REST ApplicationsDeveloping iOS REST Applications
Developing iOS REST Applications
 
Webエンジニアから見たiOS5
Webエンジニアから見たiOS5Webエンジニアから見たiOS5
Webエンジニアから見たiOS5
 
High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots
 
Dpilot - Source Code with Snapshots
Dpilot - Source Code with SnapshotsDpilot - Source Code with Snapshots
Dpilot - Source Code with Snapshots
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
Parse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & TricksParse London Meetup - Cloud Code Tips & Tricks
Parse London Meetup - Cloud Code Tips & Tricks
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
Effective iOS Network Programming Techniques
Effective iOS Network Programming TechniquesEffective iOS Network Programming Techniques
Effective iOS Network Programming Techniques
 
Edit the script in to disable code which adds demonstration entries to.pdf
Edit the script in to disable code which adds demonstration entries to.pdfEdit the script in to disable code which adds demonstration entries to.pdf
Edit the script in to disable code which adds demonstration entries to.pdf
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
 
【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例【Unity】Scriptable object 入門と活用例
【Unity】Scriptable object 入門と活用例
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)I phone勉強会 (2011.11.23)
I phone勉強会 (2011.11.23)
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 

Kürzlich hochgeladen

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Kürzlich hochgeladen (20)

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Moar tools for asynchrony!

  • 1. Moar tools for asynchrony! @nevyn
  • 2. • Background computation Building image, database search, (anything threaded) • I/O Network Disk touch app activation • Events value changes (KVO) keyboard wifi connected
  • 3. while(event = getNextEvent()) { // async event // possibly async IO, polling NSURL *pictureURL = [[Backend currentUser] profilePictureURL]; // possibly async IO NSData *pictureData = [NSData dataWithContentsOfURL:pictureURL]; // computation UIImage *profilePicture = [UIImage imageWithData:pictureData]; if ([event touches:someRect]) { // IO UIImage *highlight = [UIImage imageNamed:@"profile-picture-highlight"]; // computation profilePicture = [highlight imageCompositedOver:profilePicture]; } [profilePicture drawInRect:someRect]; }
  • 4. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions; AudioSessionAddPropertyListener( kAudioSessionProperty_AudioRouteChange, audioRouteChangeListenerCallback, NULL ); -[NSOperation setCompletionBlock:(void (^)(void))block];
  • 5. // async event - (void)touchesBegan:(NSArray*)touches withEvent:(UIEvent*)event { // async IO [[Backend currentUser] getProfilePictureURL:^ (NSURL*url) { // async IO [HTTPLibrary fetchURL:url onCompletion:^ (NSData *data) { // async processing dispatch_async(dispatch_get_global_queue(0,0), ^{ UIImage *profilePicture = [UIImage imageWithData:data]; … highlight … dispatch_async(dispatch_get_main_queue(), ^{ imageView.image = profilePicture; }; } } error:^(NSError* err) { ... }]; } onError:(NSError *err) { … }]; }
  • 6. NSString *filename = ...; NSData *maybeData = MALazyFuture(^{ return [NSData dataWithContentsOfFile: filename]; }); [object doSomethingOrNotWithData: maybeData]; NSString *filename = ...; NSData *futureData = MABackgroundFuture(^{ return [NSData dataWithContentsOfFile: filename]; }); [object doSomethingLaterWithData: futureData];
  • 7. NSString *filename = ...; Task *futureData = TCBackgroundTask(^{ return [NSData dataWithContentsOfFile: filename]; }); futureData.onDoneCallback = ^ (NSData *data) { [object doSomethingLaterWithData: futureData]; }; [futureData startOnQueue:dispatch_get_global_queue(0,0)];
  • 8. Task *task = [[Backend currentUser] profilePictureURL]; NSURL *profilePictureURL = [task runSynchronously];
  • 9. // I/O Task *pictureTask = [UIImage imageFromURL:profilePictureURL]; // computation Task *badgeTask = [UIImage imageNamedTask:@"profile-picture-highlight"]; // I/O Task *colorTask = [[Backend currentUser] favoriteColor]; // Wait for all of the above to complete [Task waitAll:pictureTask, badgeTask, colorTask, nil cancelOn:[CancellationToken cancelOnDismissed:self]]; // Use the fetched or computed values UIImage *badgedImage = [[badgeTask value] composeOnTopOf: [pictureTask value]]; UIImage *coloredImage = [badgedImage tintedImage: [colorTask value]];
  • 10. private async Task<byte[]> GetURLContentsAsync(string url) { var content = new MemoryStream(); HttpWebRequest webReq = WebRequest.Create(url); // GetResponseAsync returns a Task<WebResponse>. WebResponse response = await webReq.GetResponseAsync(); // “Pause” execution Stream responseStream = response.GetResponseStream(); // CopyToAsync returns a Task await responseStream.CopyToAsync(content); // “Pause” execution return content.ToArray(); }
  • 11. private async Task<byte[]> GetURLContentsAsync(string url) { var content = new MemoryStream(); HttpWebRequest webReq = WebRequest.Create(url); // GetResponseAsync returns a Task<WebResponse>. WebResponse response = await webReq.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); // CopyToAsync returns a Task await responseStream.CopyToAsync(content); private Task<byte[]> GetURLContentsAsync(string url) { return content.ToArray(); var content = new MemoryStream(); } HttpWebRequest webReq = WebRequest.Create(url); Task<WebResponse> responseTask = webReq.GetResponseAsync(); Task task2 = responseTask.startAndCallback(^(WebResponse response) { Stream responseStream = response.GetResponseStream(); Task copyTask = responseStream.CopyToAsync(content); Task<byte[]> bytesTask = copyTask.startAndCallback(^ { return content.ToArray(); }); return bytesTask; }; return task2; }
  • 12. TCTask* GetURLContentsAsImageAsync(NSURL *url) { return [[[NSURLConnection requestURL:url] then:^ (id response) { return [response getDataAsync]; } then:^ (NSData *data) { return TCBackgroundTask(^{ [UIImage imageWithData:data]; }); }]; }
  • 13. [[[TCRACSocket connectTo:@"localhost" port:1236] selectMany:^id<RACSubscribable>(id x) { return [x lines]; }] subscribeNext:^(id x) { self.label.text = x; } error:^(NSError *error) { NSLog(@"Failure: %@", error); }];
  • 14. • Objects <3 • Get un-stuck!

Hinweis der Redaktion

  1. Hi. I don&apos;t have a presentation as much as some material for discussion and a few thoughts. At cocoaheads here a few months ago, I realized that all the presentations were about asynchrony in some manner. Asynchrony seems to be on a lot of people&apos;s minds nowadays, more now than ever. In particular, I&apos;ve seen Microsoft doing two really interesting things recently, but we&apos;ll get to that.
  2. Let&apos;s start of by defining asynchrony: it&apos;s any task that you have to or choose to wait for the completion of. I can think of three classes of such tasks: - Background computation - I/O (network, disk, …) - Events (touch, keyboard, app activation, wifi connected, value changes ( KVO )…) Many programming languages are very sequential in nature, so how do you write code to cope with asynchrony? There are two extremely common ways: blocking, and callbacks.
  3. Blocking or synchronous code is extremely easy to follow, as every intermediate step is laid out sequentially, and dependencies are clearly visible. Fetching events, doing IO, and doing CPU-intensive work all laid out in the order it needs to. However, this (contrived) example is unacceptable, as locks up the main thread for several seconds as soon as you try to interact with the UI. It&apos;s common to use this pattern on a background thread, but this has its own set of downsides: you can&apos;t really cancel the work being done, you&apos;re locking up resources unnecessarily, and it might not even be less complex than a non-blocking counterpart since you still need to do thread communication.
  4. You&apos;ve all used callbacks in one form or another. It&apos;s a convenient pattern to be able to return from your current scope, yet return to a connected scope once your operation is complete or your event triggers. For delegating behavior, callbacks work great. Once you get to the situation where you have a chain of things you want to wait for asynchronously however, things can get really hairy.
  5. Even with fancy closures, this is pretty horrible. Error handling is spread all over the place, memory management is a mess, and this code isn&apos;t even handling cancellation. While we&apos;re using the same primitive —closures— for all the callbacks, we don&apos;t really have an abstraction for asynchrony here: we don&apos;t have a single concept wrapping all our different kind of callbacks. If we did, we might have been able to say things like &amp;quot;for all the asynchronous tasks in this method, register a cancellation handler that is triggered when this view controller goes off-screen&amp;quot;, or &amp;quot;start a UIBackgroundTask for as long as we have any outstanding IO&amp;quot;, or something much simpler like just &amp;quot;wait for all of these things to finish&amp;quot;, or &amp;quot;use this error handler for all asynchronous errors in this method&amp;quot;. In this example, we might want to set an error image whichever error we get. So, here&apos;s my current pet peeve: &amp;quot;blocking&amp;quot; and &amp;quot;callbacks&amp;quot; aren&apos;t the only two ways in which you can handle asynchronous code. Consider alternatives whenever you&apos;re writing code that is starting to resemble the above. Let&apos;s look at some.
  6. Futures are proxy objects that either don&apos;t trigger at all until you need them (upper), or runs in the background immediately but don&apos;t become blocking until you actually use them (lower). For example, if you store futureData here in an instance variable and it takes a while before you use it, you might never need to block. Since it&apos;s in the nature of Futures to actually *do* block if you ask for their value too early, I&apos;m not a big fan of them in ObjC. However, we can use them as inspiration to encapsulate asynchronous tasks in an object oriented manner.
  7. I&apos;ll admit any day to being a total Apple-head. In the past two years I&apos;ve barely even looked at anything that isn&apos;t Objective-C, and such a narrow view really isn&apos;t good for your development as a programmer. As some of you might be able to tell from this code though, I recently stumbled across some very handy concepts in C# and .NET. In C#, Task is a single class used to wrap asynchrony, no matter where it comes from. Once we have one single abstraction for asynchronous things, we can start to explore this power. If we like callbacks, we can use callbacks just like before.
  8. If we&apos;re *already* on a background thread, we can write blocking code, with the same primitives.
  9. But instead of writing sequential blocking code, we can now parallelize tasks, even though the come from different subsystems and wrap different kinds of asynchrony: in this case, computation and I/O. We can also cancel all the tasks with a single abstraction.
  10. In the C# that comes with Windows 8, they&apos;re actually building these concepts into the language. There’s a new “await” keyword that you can use whenever you encounter an asynchronous task. This actually ends execution of the method, as if you had typed “return”, and returns a Task object to the caller. The caller can then choose to either wait on it in turn, or pass it on, or whatever. When the web request comes in, the method automatically continues to execute from the point where it paused, and repeats this pattern until the method is finished. This really blew my mind, and I really hope that Apple has something similar up their sleeve next week, or they are soon going to look very stone age.
  11. Without the await keyword, the method might look something like this. I don’t really know C# so I’m faking the block syntax here... It’s the same code as before, but broken into a tree of nested closures, which is immediately a lot harder to read. However, with await, you&apos;re writing code that looks like normal, blocking sequential code, but it is in fact asynchronous and cancelable. That&apos;s pretty amazing.
  12. We don&apos;t have coroutines in Objective-C, so if we wanted to at least approximate this power in our favorite language, how might we go about it? Well, turns out that this feature is specific to C#, and in languages like Managed C++, you&apos;ll have to use chained closures. If I were to ever finish my port of this called &amp;quot;TCTask&amp;quot;, it might look a little like this. The idea is that every asynchronous task has a method called &apos;then&apos;, which calls a callback when it has finished processing. This callback can return a new TCTask which indicates more asynchronous work to be done, which you can call &apos;then&apos; on in turn, and so on and so on. This way, you end up with a chain of callbacks that look at least a bit nicer than nested callbacks, and still gives us all the flexibility of asynchrony-as-an-object that I&apos;ve been ranting about.
  13. The next really cool thing Microsoft has done recently is Reactive Extensions for C#. The whole idea behind RX is to provide tools for *composing asynchronous tasks* — basically applying functional programming tools to asynchrony. This library has been ported to cocoa in the form of ReactiveCocoa, or RAC, and is the subject for the presentation after mine, so I&apos;ll just highlight it really quickly. I experimented with wrapping AsyncSocket in RAC and ended up with something where you could write a fully working network client with error handling in 7 lines of code.
  14. To summarize, I keep relearning two life lessons in programming, and they apply to asynchrony like they do to everything else: * if you have a concept or piece of state in your code that is not represented by an actual object, go make it an object. * Don&apos;t settle for mediocrity. If you feel that your code is ugly, someone has probably thought of a way to make it pretty. If not, you can probably figure it out on your own if you give it enough thought.