Skip to content

Instantly share code, notes, and snippets.

@joshaber
Created December 7, 2012 04:57
Show Gist options
  • Save joshaber/4230872 to your computer and use it in GitHub Desktop.
Save joshaber/4230872 to your computer and use it in GitHub Desktop.
ReactiveCocoa stopwatch
self.startButton.rac_command = [RACCommand command];
self.stopButton.rac_command = [RACCommand command];
__unsafe_unretained id weakSelf = self;
id<RACSignal> tick = [[[[self.startButton.rac_command
map:^(id _) {
RTAFirstView *strongSelf = weakSelf;
// Map each start button click to a new signal that fires every second
// and stops when the stop button is clicked.
return [[RACSignal interval:1] takeUntil:strongSelf.stopButton.rac_command];
}]
// At this point we have a signal of signals. We want to just use the signal
// from the latest click.
switch]
// Increment a counter each time the signal fires.
scanWithStart:@0 combine:^(NSNumber *previous, id _) {
return @(previous.unsignedIntegerValue + 1);
}]
// Map the count to a string version of the count.
map:^(NSNumber *tick) {
return [NSString stringWithFormat:@"%lu", (unsigned long)tick.unsignedIntegerValue];
}];
// The timer label's string value should always be the latest value yield by the
// tick signal.
RAC(self.timerLabel.stringValue) = tick;
@joshaber
Copy link
Author

joshaber commented Dec 7, 2012

Of course it's not quite right since the timer restarts at the beginning of the second every time it's started instead of resuming from wherever it was before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment