iOS MVVM之ReactiveCocoa

概述

ReactiveCocoa:函数响应编程(Functional Reactive Programming, FRP)框架,目的就是定义一个统一的事件处理接口,这样它们可以非常简单地进行链接、过滤和组合。

  • 函数式编程:利用高阶函数,即将函数作为其它函数的参数。
  • 响应式编程:关注于数据流及变化的传播。

添加ReactiveCocoa框架

ReactiveCocoa框架的添加最方便是使用CocoaPods,具体步骤如下:

  • 打开终端进入项目目录
  • 执行pod init命令
  • 打开Podfile文件添加,如下图
  • 执行pod update命定

屏幕快照 2018-01-12 上午9.30.25.png

ReactiveCocoa 简介

1、首先使用Masonry搭建一个简单的登录界面,在viewDidLoad方法中添加如下代码:

    UITextField *userNameTextField = [[UITextField alloc] init];
    userNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    userNameTextField.placeholder = @"请输入用户名…";
    [self.view addSubview:userNameTextField];

    UITextField *passwordTextField = [[UITextField alloc] init];
    passwordTextField.borderStyle = UITextBorderStyleRoundedRect;
    passwordTextField.placeholder = @"请输入密码…";
    passwordTextField.secureTextEntry =  YES;
    [self.view addSubview:passwordTextField];

    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.view addSubview:loginButton];


    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.centerY.equalTo(self.view.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.equalTo(@30);
    }];
    [userNameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.bottom.equalTo(passwordTextField.mas_top).offset(-10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.equalTo(@(30));
    }];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passwordTextField.mas_left).offset(44);
        make.top.equalTo(passwordTextField.mas_bottom).offset(10);
        make.right.equalTo(passwordTextField.mas_right).offset(-44);
        make.height.equalTo(@(30));
    }];

运行效果如下图:
Simulator Screen Shot - iPhone 8 - 2018-01-12 at 10.03.51.png

2、接着在viewDidLoad方法中添加如下代码:

    [userNameTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"%@", x);
    }];

运行效果如下图:
屏幕快照 2018-01-12 上午10.16.02.png

可以看到,每次在text field中输入时,都会执行block中的代码。没有target-action,没有代理,只有信号与block。ReactiveCocoa信号发送一个事件流到它们的订阅者中。我们需要知道三种类型的事件:next, error和completed。一个信号可能由于error事件或completed事件而终止,在此之前它会发送很多个next事件。RACSignal有许多方法用于订阅这些不同的事件类型。每个方法会有一个或多个block,每个block执行不同的逻辑处理。subscribeNext:方法提供了一个响应next事件的block。ReactiveCocoa框架通过类别来为大部分标准UIKit控件添加信号,以便这些控件可以添加其相应事件的订阅。

3、RACSignal的几个操作

  • map:使用提供的block来转换事件数据。
  • filter:使用提供的block来觉得事件是否往下传递。
  • combineLatest:reduce::组合源信号数组中的信号,并生成一个新的信号。每次源信号数组中的一个输出新值时,reduce块都会被执行,而返回的值会作为组合信号的下一个值。
  • RAC宏:将信号的输入值指派给对象的属性。它带有两个参数,第一个参数是对象,第二个参数是对象的属性名。每次信号发送下一个事件时,其输出值都会指派给给定的属性。
  • rac_signalForControlEvents:从按钮的参数事件中创建一个信号。

    注意:上面的操作输出仍然是一个RACSignal对象,所以不需要使用变量就可以构建一个管道。

    扫描二维码关注公众号,回复: 2620194 查看本文章
  • doNext:附加操作,并不返回一个值。

ReactiveCocoa 简用实例

1、为登录功能增加一些需求:

  • 账号和密码都是6-16位,由数字、字母和下划线组成。
  • 账号和密码输入框在输入符合规则的时候高亮、否则置灰。
  • 账号和密码都符合规则的时候登录按钮才可用,否则置灰不可点击。
  • 登录时登录按钮不可用,并提示登录信息。

2、添加一个判断账号或密码输入有效的方法

- (BOOL)isValid:(NSString *)str {
    /*
     给密码定一个规则:由字母、数字和_组成的6-16位字符串
     */
    NSString *regularStr = @"[a-zA-Z0-9_]{6,16}";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", regularStr];
    return [predicate evaluateWithObject:str];
}

3、创建有效的账号和密码信号

    RACSignal *validUserNameSignal = [userNameTextField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        return @([self isValid:value]);
    }];
    RACSignal *validPasswordSignal = [passwordTextField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        return @([self isValid:value]);
    }];

4、将信号的输出值赋值给文本输入框的backgroundColor属性

    RAC(userNameTextField, backgroundColor) = [validUserNameSignal map:^id _Nullable(id  _Nullable value) {
        return [value boolValue] ? [UIColor clearColor] : [UIColor groupTableViewBackgroundColor];
    }];
    RAC(passwordTextField, backgroundColor) = [validPasswordSignal map:^id _Nullable(id  _Nullable value) {
        return [value boolValue] ? [UIColor clearColor] : [UIColor groupTableViewBackgroundColor];
    }];

5、组合信号并设置登录按钮是否可用

    [[RACSignal combineLatest:@[validUserNameSignal, validPasswordSignal] reduce:^id _Nonnull(id first, id second){
        return @([first boolValue] && [second boolValue]);
    }] subscribeNext:^(id  _Nullable x) {
        loginButton.enabled = [x boolValue];
    }];

6、模拟一个登录请求

- (void)loginWithUserName:(NSString *)userName password:(NSString *)password comletion:(void (^)(bool success, NSDictionary *responseDic))comletion {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([userName isEqualToString:@"Jiuchabaikaishui"]) {
            if ([password isEqualToString:@"123456"]) {
                comletion(YES, @{@"userName": userName, @"password": password, @"code": @(0), @"message": @"登录成功"});
            } else {
                comletion(YES, @{@"userName": userName, @"password": password, @"code": @(1), @"message": @"密码错误"});
            }
        } else {
            if ([userName isEqualToString:@"Jiuchabaikaishu"]) {//用账号Jiuchabaikaishu模拟网络请求失败
                comletion(NO, nil);
            } else {
                comletion(YES, @{@"userName": userName, @"password": password, @"code": @(2), @"message": @"账号不存在"});
            }
        }
    });
}

7、创建一个登录信号

    RACSignal *loginSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [self loginWithUserName:userNameTextField.text password:passwordTextField.text comletion:^(bool success, NSDictionary *responseDic) {
            if (success) {
                NSLog(@"%@", responseDic[@"message"]);
                if ([responseDic[@"code"] integerValue] == 0) {
                    [subscriber sendNext:@{@"success": @(YES), @"message": responseDic[@"message"]}];
                } else {
                    [subscriber sendNext:@{@"success": @(NO), @"message": responseDic[@"message"]}];
                }
            } else {
                NSString *message = @"请求失败";
                NSLog(@"%@", message);
                [subscriber sendNext:@{@"success": @(NO), @"message": message}];
            }
            [subscriber sendCompleted];
        }];

        return nil;
    }];

说明:createSignal:方法用于创建一个信号。描述信号的block是一个信号参数,当信号有一个订阅者时,block中的代码会被执行。block传递一个实现RACSubscriber协议的subscriber(订阅者),这个订阅者包含我们调用的用于发送事件的方法;我们也可以发送多个next事件,这些事件由一个error事件或complete事件结束。在上面这种情况下,它发送一个next事件来表示登录是否成功,后续是一个complete事件。这个block的返回类型是一个RACDisposable对象,它允许我们执行一些清理任务,这些操作可能发生在订阅取消或丢弃时。上面这个这个信号没有任何清理需求,所以返回nil。

8、响应按钮点击事件,登录成功进入主页

    [[[[loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] doNext:^(__kindof UIControl * _Nullable x) {
        [MBProgressHUD showHUDAddedTo:self.view animated:NO];
        [self.view endEditing:YES];
        loginButton.enabled = NO;
    }] flattenMap:^id _Nullable(__kindof UIControl * _Nullable value) {
        return loginSignal;
    }] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        loginButton.enabled = YES;
        if ([x[@"success"] boolValue]) {
            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [delegate gotoMainViewController];
        } else {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:NO];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = x[@"message"];
            hud.label.numberOfLines = 0;
            [hud hideAnimated:YES afterDelay:3];
        }
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        loginButton.enabled = YES;
    }];

说明:
- 为什么要创建一个登录信号,而不是直接使用登录方法?因为登录方法是一个异步操作。
- 为什么使用flattenMap来替换map?因为当点击按钮时rac_signalForControlEvents发出了一个next事件。flattenMap这一步创建并返回一个登录信号,意味着接下来的管理接收一个RACSignal,这是我们在subscribeNext:中观察到的对象——信号的信号(signal of signals),换句话说,就是一个外部信号包含一个内部信号。flattenMap可以在输出信号的subscribeNext:块中订阅内部信号。map在这会引起嵌套的麻烦。

内存管理

  • ReactiveCocoa维护了一个全局的信号集合。如果信号有一个或多个订阅者,它就是可用的。如果所有订阅者都被移除了,信号就被释放了。
  • 如何取消对信号的订阅?在一个completed事件或error事件后,一个订阅者会自动将自己移除。手动移除可能通过RACDisposable来完成。RACSignal的所有订阅方法都返回一个RACDisposable实例,我们可以调用它的dispose方法来手动移除订阅者。
  • 注意:如果我们创建了一个管道,但不去订阅它,则管道永远不会执行,包括任何如doNext:块这样的附加操作。
  • @weakify@strongifyExtendedobjc库中引用,它们包含在ReactiveCocoa框架中。@weakify允许我们创建一些影子变量,它是都是弱引用(可以同时创建多个),@strongify允许创建变量的强引用,这些变量是先前传递给@weakify的。当在block中使用实例变量时,block同样会捕获self的一个强引用。
    @weakify(self)
    RACSignal *validUserNameSignal = [userNameTextField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        @strongify(self)
        return @([self isValid:value]);
    }];

搭建主页界面

这是一个好友的显示界面,有一个搜索和退出功能。

//设置UI
    self.title = @"首页";
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [leftButton setTitle:@"退出" forState:UIControlStateNormal];
    [[leftButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if ([self.delegate respondsToSelector:@selector(logout:message:)]) {
            [self.delegate logout:YES message:nil];
        }
    }];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
    UITextField *textField = [[UITextField alloc] init];
    [textField setBorderStyle:UITextBorderStyleRoundedRect];
    textField.placeholder = @"搜索好友";
    self.navigationItem.titleView = textField;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.top.equalTo(@(0));
        make.width.equalTo(@([UIScreen mainScreen].bounds.size.width - 60));
        make.height.equalTo(@(30));
    }];

    UITableView *tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:tableView];
    self.tableView = tableView;

获取数据

  • 模拟一个取数据和一个搜索数据的接口
- (void)gettingData:(void (^)(BOOL success, NSArray *friends))completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"]];
        NSError *error = nil;
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        [NSThread sleepForTimeInterval:3];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                if (completion) {
                    completion(NO, nil);
                }
            } else {
                if (completion) {
                    NSMutableArray *mArr = [NSMutableArray arrayWithCapacity:1];
                    for (NSDictionary *dic in arr) {
                        [mArr addObject:[FriendModel friendModelWithInfo:dic]];
                    }
                    completion(YES, mArr);
                }
            }
        });
    });
}
- (void)searchFriends:(NSString *)content completion:(void (^)(BOOL success, NSArray *friends)) completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.allFriends) {
                if (completion) {
                    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name like '*%@*' or uin like '*%@*'", content, content]];//name beginswith[c] %@
                    completion(YES, [self.allFriends filteredArrayUsingPredicate:predicate]);
                } else {
                    if (completion) {
                        completion(NO, nil);
                    }
                }
            }
        });
    });
}
  • 创建获取数据与搜索数据的信号
    @weakify(self)
    RACSignal *dataSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self)
        [MBProgressHUD showHUDAddedTo:self.view animated:NO];
        [self gettingData:^(BOOL success, NSArray *friends) {
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            if (success) {
                self.allFriends = [NSArray arrayWithArray:friends];
                self.friends = self.allFriends;
                [textField becomeFirstResponder];
                [subscriber sendNext:friends];
                [subscriber sendCompleted];
            } else {
                [subscriber sendError:[NSError errorWithDomain:@"NetError" code:1 userInfo:@{@"message": @"网络请求失败"}]];
            }
        }];

        return nil;
    }];
    RACSignal *searchSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self)
        [self searchFriends:textField.text completion:^(BOOL success, NSArray *friends) {
            NSArray *arr;
            if (success) {
                arr = friends;
            } else {
                arr = self.allFriends;
            }

            [subscriber sendNext:arr];
            [subscriber sendCompleted];
        }];

        return nil;
    }];
  • 连接信号
    [[[[[[dataSignal then:^RACSignal * _Nonnull{
        return textField.rac_textSignal;
    }] filter:^BOOL(id  _Nullable value) {
        @strongify(self)
        NSString *text = (NSString *)value;
        if (text.length == 0) {
            if (![self.friends isEqual:self.allFriends]) {
                self.friends = self.allFriends;
            }
        }
        return text.length > 0;
    }] throttle:0.5] flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
        return searchSignal;
    }] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        self.friends = (NSArray *)x;
    }];

说明:
1、一旦用户获取了所有的好友数据,程序需要继续监听文本框的输入,以搜索好友。
2、then方法会等到completed事件发出后调用,然后订阅由block参数返回的信号。这有效地将控制从一个信号传递给下一个信号。
3、添加一个filter操作到管道,以移除无效的搜索操作。
4、使用flattenMap来将每个next事件映射到一个新的被订阅的信号。
5、deliverOn:线程操作,确保接下来的UI处理会在主线程上。
6、一个更好的方案是如果搜索文本在一个较短时间内没有改变时我们再去执行搜索操作,throttle操作只有在两次next事件间隔指定的时间时才会发送第二个next事件。

展示数据

  • 完成UITableView的代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.friends ? 1 : 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.friends.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    FriendModel *model = [self.friends objectAtIndex:indexPath.row];
    cell.textLabel.text = model.name;
    cell.detailTextLabel.text = model.uin;
    cell.imageView.image = [UIImage imageNamed:@"50"];

    return cell;
}
  • 异步加载图片
    //异步加载图片
    [[[RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:model.img]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [subscriber sendNext:data];
            });
        });
        return nil;
    }] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id  _Nullable x) {
        [cell.imageView setImage:[UIImage imageWithData:x]];
    }];

效果展示和代码下载

Simulator Screen Shot - iPhone 8 - 2018-01-25 at 15.58.24.png

下载代码请猛戳

猜你喜欢

转载自blog.csdn.net/jiuchabaikaishui/article/details/79163144