美文网首页
ReactiveCocoa笔记1

ReactiveCocoa笔记1

作者: wata | 来源:发表于2018-02-09 15:05 被阅读4次

    ReactiveCocoa笔记

    1. map:方法可以转换信号,将一个信号处理后转变为另一个信号,例如:
    RACSignal *validUsernameSignal = [self.usernameTextField.rac_textSignal
          map:^id(NSString *text) {
            return @([self isValidUsername:text]);
          }];
    
    1. RAC(TARGET, ...)宏可以用keyValue的方式使用信号中的值给object的key赋值,例如:
    RAC(self.passwordTextField, backgroundColor) =
        [validPasswordSignal
          map:^id(NSNumber *passwordValid) {
            return [passwordValid boolValue] ? [UIColor clearColor] : [UIColor yellowColor];
          }];
    
    1. combineLatest:方法可以组合多个信号,变为一个信号,例如:
    RACSignal *signUpActiveSignal =
        [RACSignal combineLatest:@[validUsernameSignal, validPasswordSignal]
                          reduce:^id(NSNumber *usernameValid, NSNumber *passwordValid) {
                            return @([usernameValid boolValue] && [passwordValid boolValue]);
                          }];
    
    1. 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];
         }
       }];
    
    1. 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上的

    ReactiveCocoa Tutorial – The Definitive Introduction: Part 1/2

    相关文章

      网友评论

          本文标题:ReactiveCocoa笔记1

          本文链接:https://www.haomeiwen.com/subject/givftftx.html