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

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

Shake Effect in iOS

Animation Animation always capture the user attention. We can use animation to update things on the screen.  For developer also animations fascinated things to learn and implement. Today we will try shake effect with Various  API. CABasicAnimation: Here we animate view's frame y coordinate from one position to another position. It is simple example of changing the position with respect to time. CABasic Animation is deal with the single keyframe.                                        y(t) = y 0 + t*d(y) You can use CABasic Animation if you have to play with single value. You need to move object from  one position to another without any intermediate steps. CABasicAnimation * shakeAnimation = [CABasicAnimation animationWithKeyPath: @ "position" ]; shakeAnimation . duration = 0.05 ; shakeAnimation . autoreverses = YES; shakeAnimation . repe...

NSThread with Asynchronous Request

NSThread: It is class used in Cocoa framework to create a thread.You have to specify a target and selector to create a new thread in objective c. So the selector or method is main entry point of your thread.  Detail: What happen once the thread execute all the code in the method (Thread main routine)? Thread is terminated after execute all the code in the entry(its main routine) routine. So how we can run an asynchronous request on NSThread ? What is Async request? It is non blocking request which permit the application to do other task side by side as request is in continue. So it enhance parallelism in the application. Now question is how we can prepare a asynchronous request in iOS: - ( void ) startAsyncRequestWithUrl:( NSString *)urlString{     assert (urlString != nil && urlString. length > 0 );     NSURL * url = [[ NSURL alloc ] initWithString :urlString];     NSURLRequest * urlRequest = [[ NSURLReq...