Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check a dispatch queue is empty or not?

My condition is that when I scroll my tableview to the bottom or to the top, I need to do some reload, refresh job that will ask for new data from the server, but I want to check if the last job is done or not. If the last request is still working, I should not fire another request.

I'm using the same background queue created from dispatch_queue_create() to deal with the httpRequest.

- (id)init {
    self = [super init];
    if (self) {
        ...
        dataLoadingQueue = dispatch_queue_create(@"DataLoadingQueue", NULL);
    }
    return self;
}

From now on, I just use a BOOL value to detect if the job is on working or not. Something like this:

if(!self.isLoading){

    dispatch_async(dataLoadingQueue, ^{

        self.isLoading = YES;
        [self loadDataFromServer];

    });

}

I just wonder if there is any way to change the code to be like the following:

if(isQueueEmpty(dataLoadingQueue)){

    dispatch_async(dataLoadingQueue, ^{

        [self loadDataFromServer];

    });

}

Thus I can remove the annoying BOOL value that shows everywhere and need to keep tracking on.

like image 810
林鼎棋 Avatar asked Mar 18 '15 02:03

林鼎棋


1 Answers

Why don't you instead use NSOperationQueue (check [operationQueue operationCount]) ?

If you just want to use GCD, dispatch_group_t may be fit you.

@property (atomic) BOOL isQueueEmpty;
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_async(dispatchGroup, dataLoadingQueue, ^{
    self.isQueueEmpty = NO;
    //Do something
});

dispatch_group_notify(dispatchGroup, dataLoadingQueue, ^{
    NSLog(@"Work is done!");
    self.isQueueEmpty = YES;
});

While tasks have completed, the group will be empty and trigger the notification block in dispatch_group_notify.

like image 98
Jamin Zhang Avatar answered Oct 12 '22 01:10

Jamin Zhang