Created
October 23, 2018 20:17
-
-
Save supermarin/8e9484af76ca719fb9a31dea0109612f to your computer and use it in GitHub Desktop.
fetching cached configuration using dispatch groups and early return
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface ViewController () | |
@end | |
@implementation ViewController | |
static dispatch_queue_t serialq; | |
static dispatch_queue_t concurrentq; | |
- (void)getConfigurationWithCompletion:(void (^)(NSString *))completionBlock { | |
static NSString *configuration; | |
dispatch_async(serialq, ^{ | |
if (configuration) { | |
NSLog(@"returning cached config."); | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
completionBlock(configuration); | |
}); | |
return; | |
} | |
NSLog(@"grouping..."); | |
dispatch_group_t group = dispatch_group_create(); | |
dispatch_group_enter(group); | |
[self GET:^(NSString *result) { | |
configuration = result; | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
completionBlock(configuration); | |
}); | |
dispatch_group_leave(group); | |
}]; | |
dispatch_group_wait(group, DISPATCH_TIME_FOREVER); | |
}); | |
} | |
- (void)GET:(void (^)(NSString *))completionBlock { | |
dispatch_async(concurrentq, ^{ | |
NSLog(@"requesting network..."); | |
sleep(1); | |
NSLog(@"network request done..."); | |
completionBlock(@"WAT"); | |
}); | |
} | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
// Do any additional setup after loading the view, typically from a nib. | |
concurrentq = dispatch_queue_create("work q", DISPATCH_QUEUE_CONCURRENT); | |
serialq = dispatch_queue_create("exec q", DISPATCH_QUEUE_SERIAL); | |
} | |
- (void)viewDidAppear:(BOOL)animated { | |
[super viewDidAppear:animated]; | |
for (int i = 1; i <= 5; i ++) { | |
NSLog(@"Getting configuration for the %d time.", i); | |
[self getConfigurationWithCompletion:^(NSString *conf) { | |
NSLog(@"Got configuration %d: %@", i, conf); | |
}]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment