Synchronous calls in an asynchronous environment

78 views Asked by At

I am using AFNetworking 2.0 and Objective-C to create a class which synchronizes the client database with the database on the server. Of course, the client shouldn't notice when this happens, so the class has to make the calls asynchronous. However, some calls in this class are dependent on the results of others calls.

Example:

  • Object: Mammal, id = 15, new id = 26
  • Subobject: Zebra, clade_id = 15

The zebra can only update its properties once the mammals are done, because it uses some of the mammals properties (id) and if it sends the call too early it results in corrupted data (id = 15 instead of the correct 26).

My question is, how one could use AFNetworking to make these synchronous calls (zebra after mammal has finished) in a way that the user doesn't notice (asynchronous).

Thanks for your answers.

1

There are 1 answers

1
Serge Maslyakov On BEST ANSWER

You not need to use a synchronous calls.

1) The first way

// create request with URL
NSMutableURLRequest *request = ....;

// create AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationManager manager] HTTPRequestOperationWithRequest:request success:^{success block} failure:^{failure block}];

// Call operation
[self.operationQueue addOperation:operation];

In the success block you schedule second operation.

2) The second way
Create both operations at once and set the first operation how dependency for the second operation (but need the additional code for managing shared data).

[operation2 addDependency:operation1]; 
[self.operationQueue addOperation:operation1];
[self.operationQueue addOperation:operation2];