Created
December 8, 2012 02:54
-
-
Save joshaber/4238342 to your computer and use it in GitHub Desktop.
ReactiveCocoa stopwatch with reset
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
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