ReactiveCocoa笔记
- map:方法可以转换信号,将一个信号处理后转变为另一个信号,例如:
RACSignal *validUsernameSignal = [self.usernameTextField.rac_textSignal
map:^id(NSString *text) {
return @([self isValidUsername:text]);
}];
- RAC(TARGET, ...)宏可以用keyValue的方式使用信号中的值给object的key赋值,例如:
RAC(self.passwordTextField, backgroundColor) =
[validPasswordSignal
map:^id(NSNumber *passwordValid) {
return [passwordValid boolValue] ? [UIColor clearColor] : [UIColor yellowColor];
}];
- combineLatest:方法可以组合多个信号,变为一个信号,例如:
RACSignal *signUpActiveSignal =
[RACSignal combineLatest:@[validUsernameSignal, validPasswordSignal]
reduce:^id(NSNumber *usernameValid, NSNumber *passwordValid) {
return @([usernameValid boolValue] && [passwordValid boolValue]);
}];
- doNext:可以添加signal流的响应事件而不改变当前的管道流,我们称它为side-effect,side-effect不改变信号的转变,只是做出响应:例子如下:
[[[[self.signInButton
rac_signalForControlEvents:UIControlEventTouchUpInside]
doNext:^(id x) {
self.signInButton.enabled = NO;
self.signInFailureText.hidden = YES;
}]
flattenMap:^id(id x) {
return [self signInSignal];
}]
subscribeNext:^(NSNumber *signedIn) {
self.signInButton.enabled = YES;
BOOL success = [signedIn boolValue];
self.signInFailureText.hidden = success;
if (success) {
[self performSegueWithIdentifier:@"signInSuccess" sender:self];
}
}];
- flattenMap:可以取出signal的signal.当我们使用map:的时候,直接return一个value,系统便会自动封装成一个新的signal.但是当返回的value本身就是一个signal的时候,系统还是会帮我们在包一层signal, 所以,这种情况下,我们取药的是最里面的signal,而不是系统在外层帮我们包裹的signal.所以这种情况下就会使用flattenMap:而不是map:,还是上面的代码
[[[[self.signInButton
rac_signalForControlEvents:UIControlEventTouchUpInside]
doNext:^(id x) {
self.signInButton.enabled = NO;
self.signInFailureText.hidden = YES;
}]
flattenMap:^id(id x) {
return [self signInSignal];
}]
subscribeNext:^(NSNumber *signedIn) {
self.signInButton.enabled = YES;
BOOL success = [signedIn boolValue];
self.signInFailureText.hidden = success;
if (success) {
[self performSegueWithIdentifier:@"signInSuccess" sender:self];
}
}];
详细工程参见raywenderlich上的