Created
November 21, 2013 16:54
-
-
Save Strilanc/7585407 to your computer and use it in GitHub Desktop.
Code for NSNotificationCenter subscription controlled by cancellation token.
This file contains 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
#import <XCTest/XCTest.h> | |
#import "TwistedoakCollapsingFutures.h" | |
#define notificationName @"note" | |
static int counter = 0; | |
@interface NSNotificationCenter (CancelToken) | |
-(void) addObserverForName:(NSString*)name | |
until:(TOCCancelToken*)untilCancelledToken | |
usingBlock:(void(^)(NSNotification*))block; | |
@end | |
@implementation NSNotificationCenter (CancelToken) | |
-(void) addObserverForName:(NSString*)name | |
until:(TOCCancelToken*)untilCancelledToken | |
usingBlock:(void(^)(NSNotification*))block { | |
id subscription = [self addObserverForName:name | |
object:nil | |
queue:nil | |
usingBlock:block]; | |
[untilCancelledToken whenCancelledDo:^{ | |
[self removeObserver:subscription]; | |
}]; | |
} | |
@end | |
@interface Attempt : NSObject | |
@property int localCounter; | |
@end | |
@implementation Attempt | |
@synthesize localCounter; | |
-(id)initUntil:(TOCCancelToken*)untilCancelledToken { | |
if (self = [super init]) { | |
NSNotificationCenter* c = NSNotificationCenter.defaultCenter; | |
[c addObserverForName:notificationName | |
until:untilCancelledToken | |
usingBlock:^(NSNotification *note) { | |
int oldCounterValue = counter; | |
counter++; | |
self.localCounter++; | |
NSAssert(counter==oldCounterValue+1, @"Atomicity guarantee violated."); | |
}]; | |
} | |
return self; | |
} | |
@end | |
@interface Test2Tests : XCTestCase | |
@end | |
@implementation Test2Tests | |
-(void)testExample { | |
for(int i =0; i < 5; i++) { | |
TOCCancelTokenSource* c = [TOCCancelTokenSource new]; | |
Attempt *a = [[Attempt alloc] initUntil:c.token]; | |
[NSNotificationCenter.defaultCenter postNotificationName:notificationName object:nil]; | |
[c cancel]; | |
XCTAssertEqual(counter, i+1, @"Unexpected value for counter."); | |
XCTAssertEqual(1, a.localCounter, @"Unexpected value for localCounter."); | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment