Created
December 7, 2012 04:57
-
-
Save joshaber/4230872 to your computer and use it in GitHub Desktop.
ReactiveCocoa stopwatch
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
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.