Skip to content

Instantly share code, notes, and snippets.

@joshaber
Created December 8, 2012 02:54
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshaber/4238342 to your computer and use it in GitHub Desktop.
Save joshaber/4238342 to your computer and use it in GitHub Desktop.
ReactiveCocoa stopwatch with reset
self.startButton.rac_command = [RACCommand command];
self.stopButton.rac_command = [RACCommand command];
self.resetButton.rac_command = [RACCommand command];
static const CGFloat interval = 0.01;
__unsafe_unretained id weakSelf = self;
// Signal id -> Signal Signal Number
// Map each click of the start button to a signal that fires at our interval
// and stops when the stop button's clicked.
id<RACSignal> start = [self.startButton.rac_command map:^(id _) {
RTAFirstView *strongSelf = weakSelf;
return [[[RACSignal
interval:interval]
mapReplace:@1]
takeUntil:strongSelf.stopButton.rac_command];
}];
// Signal id -> Signal Signal Number
// Map each click of the reset button to a signal that simply sends a 0.
id<RACSignal> reset = [self.resetButton.rac_command map:^(id _) {
return [RACSignal return:@0];
}];
// [Signal Signal Number] -> Signal String
id<RACSignal> tick = [[[[RACSignal
// By merging start and reset, we'll get the most recent signal to yield
// a value. Then we'll switch to use the latest signal.
merge:@[ start, reset ]]
switch]
// Increment the tick count and multiply it by the multiplier our
// current signal has sent us.
scanWithStart:@0 combine:^(NSNumber *previous, NSNumber *multiplier) {
return @((previous.doubleValue + interval) * multiplier.doubleValue);
}]
// Map the ticket to a string representation.
map:^(NSNumber *tick) {
return [NSString stringWithFormat:@"%.2f", (double)tick.doubleValue];
}];
RAC(self.timerLabel.stringValue) = tick;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment