Skip to main content

How to Handle Multiple Asynchronous Response (Wait to complete All)

Background :

Suppose you are developing an application and you need to hit multiple Asynchronous request at a time. Now you are waiting for the responses from all the request to be complete.

Question is When you received any response in a delegate, callback or Completion block, how to ensure whether all the request is completed or not ?



There can be many ways to do this. I am explaining here two ways to handle this:

1) Use a simple Counter (Preferred for same type of request)

2) Use a enum with Bitwise Method

Logical Explanation:

Use a simple Counter:

In this approach we need to use a counter. For every request we will increase the counter by 1 and when we receive the response, decrement it by 1. This approach is good if we have only one type of request. Like image downloading for gallery. In this approach we cannot differentiate that which request is completed or which is not.

Use a enum with Bitwise Method

In this approach we will use enum to keep track of the request. Enum will have value as particular bit position is set.

Like 
typedef enum{
        request1 1<<0   //First bit can be set using this
        request1 1<<1   //Second bit can be set using this
        request1 1<<2   //Third bit can be set using this
}request;

We will take an integer and use '|' operand to set particular bit, Once we have the response.

Pros:  We can even track whether particular request is completed or not. By using "&" operand with integer to check value is set or not.

Implementation:

Use a simple Counter:

Let suppose you have a url connection custom class. Using that you are hitting a web service asynchrony. You need to take a counter and increment it when you are creating a request.  

You have a controller in which you need to download the image from the url and you have array of image url list. Then your implementation can be following:

ViewController.h

@interface FlickerViewController : UIViewController

@property (nonatomic, strong)NSArray*   imageURLList;

@end

ViewController.m

#import "FlickerViewController.h"

@interface FlickerViewController ()

@property (atomic, assign)NSUInteger requestCount;

@end

@implementation FlickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.requestCount = self.imageURLList.count;
    for (NSString* imageUrl in self.imageURLList) {
        //request for image downloading
    }
}

//Completion block
- (void) downloadManager:(id)manager didCompleteWithResponse:(id)response{
    self.requestCount--;
    if(self.requestCount == 0){
        //Congrats your all request completed
    }

}


Your completion implementation can be different you can use blocks as well but request complete check logic will be same. Yes for thread safety i am using atomic for the property. You can apply other method as well.

Use a enum with Bitwise Method


Let Suppose while loading a view controller you need to fetch user info and user friend list asynchronously. You need to wait until both the request complete. If user info request failed then you need to show error alert. If user friend list fail then no need to show anything just do not display the user friend list.


ViewController.m

#import "FlickerViewController.h"

typedef enum {
    UserDataRequestUserInfoComplete =  1<<0,
    UserDataRequestUserFriendListComplete =  1<<1,
    UserDataRequestUserInfoFailed   =  1<<2,
    UserDataRequestUserFriendListFailed   =  1<<3
}UserDataRequestStatus;

@interface FlickerViewController ()

@property (nonatomic, assign)NSUInteger requestComplete;

- (void) loadUserInfo;
- (void) loadUserFreindList;

@end



@implementation FlickerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //send Async request for laoding
    [self loadUserInfo]; //Async Request
    [self loadUserFreindList]; //Async Request
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void) loadUserInfo{
    
    __weak __typeof(self) weakSelf = self;
    
    [ServerManager loadUserInfoWithCompletionBlock:^(id response, BOOL isError, NSError* error){
        if(isError ||  error != nil){
            weakSelf.requestComplete |= UserDataRequestUserInfoFailed;
            //Do logic to show alert
            return;
        }
        if([weakSelf isAllRequestSucceed]){
            //Do your logic
        }else if(self.requestComplete & UserDataRequestUserFriendListFailed){
            //reload page with data
        }
    }];
    
}
- (void) loadUserFreindList{
    [ServerManager loadUserFriendListWithCompletionBlock:^(id response, BOOL isError, NSError* error){
        if(isError ||  error != nil){
            weakSelf.requestComplete |= UserDataRequestUserFriendListFailed;
            return;
        }
        if([weakSelf isAllRequestSucceed]){
            //Do your logic after all complete
        }else if(self.requestComplete & UserDataRequestUserInfoFailed){
            //Do not display anything
        }
        
        
    }];
}

- (BOOL) isAllRequestSucceed{
    if((self.requestComplete & UserDataRequestUserInfoComplete) && (self.requestComplete & UserDataRequestUserFriendListComplete)){
        return true;
    }
    return false;
}

@end

In the above case we use completion block and check if all the request is completed then display the view.

There will be more ways to handle the multiple Asynchronous response. If you have better approach then we can discuss it here.

Please provide your comments on this and let me know if any help required.




Comments

Popular posts from this blog

Best Practices in iOS with Objective - C

In this post i am making collection of points which i read from some other post or some documentation. Today we will learn what are good or bad habits while doing programming in objective - c. 1) Instance Type and id I noticed one day that in iOS SDK init method of class has  instancetype  as a return value. I am curious to know about this thing and why this type not id. So what i found is following: Example: - ( instancetype )initWithProximityUUID:( NSUUID *)proximityUUID identifier:( NSString *)identifier What is instancetype? Suppose you are writing a method for object initialisation and according to objective c coding convention you need to return the object of same class from the method. So you can use instance type as a return type of method. Instance Type -  It represents the instance of the class or subclass of the class in which you are writing the method with return type instancetype. Confusing ? Let suppose i have declare a class empl...

What does enable bitcode do in Xcode

Background: Now days compilation process for any language is divided into two parts and same is applicable for objective c. Frontend Compiler (Clang) Backend Compiler (LLVM) Frontend Compiler (Clang):  Responsibility of front-end compiler is to take a source code and convert into intermediate representation (IR).  In case of clang it is LLVM IR.  Backend Compiler(LLVM):  Responsibility of backend compiler is to take a IR as input and convert into object code. LLVM input is bitstream of LLVM IR (Bitcode) and output is sequence of machine instruction(Object code). Each  cpu or processor has different set of  M achine   instruction, So  LLVM output is CPU dependent or it can be executed on specific CPU only.   There may be question in your mind that  1) What is the need to divide into these phases? 2) What is LLVM IR? Can we see the LLVM IR as Output? What is the need to divid...

Asynchronous Request with NSOperationQueue

Today post is about how to run a asynchronous task in NSOperationQueue.  Generally we do not run a Asynchronous task in NSOperationQueue. It is also not recommended for any programmer to do that. This post is only for learning purpose what will happen if we schedule a asynchronous task in a queue and how can we complete that task:). So let us move to the learning: NSOperationQueue: In iOS NSOperationQueue is a class, which provide a way to perform operation concurrently. We also have others way to perform concurrent operation: 1) GCD 2) NSThread 3) pThread NSOperationQueue is a wrapper on GCD, which provides a very convenient way to execute operation concurrently. To create a Queue for Operation you have to simply allocate a object of the class: NSOperationQueue * opertionQueue = [[ NSOperationQueue alloc ] init ]; For this post let suppose you are making a queue to handle all Http request in your application. So i want to create a queue in Handl...