iOS开发攻城狮的集散地iOS DeveloperMVVM+RAC

iOS MVVM之ReactiveCocoa

2018-01-25  本文已影响1179人  酒茶白开水

概述

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

添加ReactiveCocoa框架

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

屏幕快照 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的几个操作

ReactiveCocoa 简用实例

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

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;
    }];

说明:

内存管理

    @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事件。

展示数据

- (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

下载代码请猛戳

上一篇 下一篇

猜你喜欢

热点阅读