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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With